2023年7月22日发(作者:)
c语⾔线程的join详解,pthread_joinpthread_exit⽤法实例函数pthread_join⽤来等待⼀个线程的结束。函数原型为:extern int pthread_join __P ((pthread_t __th, void **__thread_return));第⼀个参数为被等待的线程标识符,第⼆个参数为⼀个⽤户定义的指针,它可以⽤来存储被等待线程的返回值。这个函数是⼀个线程阻塞的函数,调⽤它的线程将 ⼀直等待到被等待的线程结束为⽌,当函数返回时,被等待线程的资源被收回。⼀个线程的结束有两种途径,⼀种是象我们上⾯的例⼦⼀样,函数结束了,调⽤它的 线程也就结束了;另⼀种⽅式是通过函数pthread_exit来实现。它的函数原型为:extern void pthread_exit __P ((void *__retval)) __attribute__ ((__noreturn__));唯⼀的参数是函数的返回代码,只要pthread_exit中的参数retval不是NULL,这个值将被传递给 thread_return。最后要说明的是,⼀个线程不能被多个线程等待,否则第⼀个接收到信号的线程成功返回,其余调⽤pthread_join的线 程则返回错误代码ESRCH。实例:/*myfile11-3.c*/#include#include#includepthread_t tid1, tid2;void *tret;void *thr_fn1(void *arg){sleep(1);//睡眠⼀秒,等待TID2结束。pthread_join(tid2, &tret);//tid1⼀直阻赛,等到tid2的退出,获得TID2的退出码printf("thread 2 exit code %dn", (int)tret);printf("thread 1 returningn");return((void *)2);}void *thr_fn2(void *arg){printf("thread 2 exitingn");pthread_exit((void *)3);}intmain(void){int err;err = pthread_create(&tid1, NULL, thr_fn1, NULL);if (err != 0)printf("can't create thread 1n");err = pthread_create(&tid2, NULL, thr_fn2, NULL);if (err != 0)printf("can't create thread 2n");err = pthread_join(tid1, &tret);//祝线程⼀直阻赛,等待TID1的返回。if (err != 0)printf("can't join with thread 1n");printf("thread 1 exit code %dn", (int)tret);//err = pthread_join(tid2, &tret);//if (err != 0)// printf("can't join with thread 2n");// printf("thread 2 exit code %dn", (int)tret);exit(0);}命令:#gcc -lthread myfile11-3.c:#./运⾏结果:thread 2 exitingthread 2 exit code 3thread 1 returningthread 1 exit code 2
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1689988397a298538.html
评论列表(0条)