linux多线程学习(1)

基本函数和关系

 

 pthread_create创建一个子线程;

pthread_exit是线程函数在终止执行时调用,就像进程在执行完毕以后调用exit函数一样;

pthread_join制定了主进程将要等待的子进程,该函数将阻塞主进程执行,直到子进程执行完毕,类似于wait函数。

测试代码(参考《Linux程序设计》一书):

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 #include <pthread.h>
 6 
 7 char message[] = "hello,world!";
 8 void* thread_func(void *arg)
 9 {
10     printf("thread function is running. Argument is %s\n",(char*)arg);
11     sleep(3);
12     strcpy(message, "Bye!");
13     pthread_exit("this is the exit message");
14 }
15 
16 int main(void)
17 {
18     int res;
19     pthread_t tid;
20     void *thread_result;
21     res=pthread_create(&tid,NULL,thread_func,(void*)message);
22     if(res!=0)
23     {
24         perror("Thread create failed");
25         exit(EXIT_FAILURE);
26     }
27     
28     res=pthread_join(tid,&thread_result);
29     if(res!=0)
30     {
31         perror("Thread join failed");
32         exit(EXIT_FAILURE);
33     }
34     
35     printf("Thread joined, it returned: %s\n",(char*)thread_result);
36     printf("now message is: %s\n",message);
37     exit(EXIT_SUCCESS);
38 }

执行结果为:

 

 主进程在创建子进程以后,通过join等待子进程执行,同时, 子进程休眠3秒以后,将传入的参数修改,并返回了“this is the exit message”。

join函数收到了该返回值,并将其传递给了thread_result,最后,显示全局变量message被修改了。

 

posted @ 2021-01-09 15:35  castor_xu  阅读(81)  评论(0编辑  收藏  举报