多线程

来源:互联网 发布:用友软件使用说明书 编辑:程序博客网 时间:2024/06/07 01:14
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

void* thread_function(void *arg);

char message[] = "hello world";

int main(){
    int res;
    pthread_t a_thread;
    void *thread_result;

    res = pthread_create(&a_thread, NULL,
                 thread_function,
                 (void *)message);
    if(res){
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }

    sleep(1);

    printf("waiting for thread to finish...\n");
    res = pthread_join(a_thread, &thread_result);
    if(res){
        perror("thread join failed");
        exit(EXIT_FAILURE);
    }
    printf("thread joined, it returned %s\n",
        (char*)thread_result);
    printf("message is now %s\n", message);
    exit(EXIT_SUCCESS);
}


void*thread_function(void *arg){
    printf("thread_function is running.Argument was %s\n",
        (char*)arg);
    sleep(3);
    strcpy(message, "bye!");
    pthread_exit("thank you for the cpu time");
}

$ gcc test.c -lpthread
$ ./a.out

thread_function is running.Argument was hello world
waiting for thread to finish...
thread joined, it returned thank you for the cpu time
message is now bye!


0 0
原创粉丝点击