POSIX的pthread_join

join

  • join是三种同步线程的方式之一。另外两种分别是互斥锁(mutex)和条件变量(condition variable)。
  • 调用pthread_join()将阻塞自己,一直到要等待加入的线程运行结束。
  • 可以用pthread_join()获取线程的返回值。
  • 一个线程对应一个pthread_join()调用,对同一个线程进行多次pthread_join()调用是逻辑错误。

join or detach

  • 线程分两种:一种可以join,另一种不可以。该属性在创建线程的时候指定。
  • joinable线程可在创建后,用pthread_detach()显式地分离。但分离后不可以再合并。该操作不可逆。
  • 为了确保移植性,在创建线程时,最好显式指定其join或detach属性。似乎不是所有POSIX实现都是用joinable作默认。
[cpp]  view plain copy
  1. #include <pthread.h>  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #define NUM_THREADS 4  
  5.   
  6. void *BusyWork(void *t)  
  7. {  
  8.     double result=0.0;  
  9.     long tid = (long)t;  
  10.     printf("Thread %ld starting...\n",tid);  
  11.     for (int i=0; i<1000000; i++)  
  12.     {  
  13.         result = result + sin(i) * tan(i);  
  14.     }  
  15.     printf("Thread %ld done. Result = %e\n",tid, result);  
  16.     pthread_exit((void*) t);  
  17. }  
  18.   
  19. int main (int argc, char *argv[])  
  20. {  
  21.     pthread_t thread[NUM_THREADS];  
  22.     pthread_attr_t attr;  
  23.   
  24.     // 1/4: init  
  25.     pthread_attr_init(&attr);  
  26.     // 2/4: explicitly specify as joinable or detached  
  27.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);  
  28.   
  29.     int rc;  
  30.     long t;  
  31.     for(t=0; t<NUM_THREADS; t++)  
  32.     {  
  33.         printf("Main: creating thread %ld\n", t);  
  34.         // 3/4: use thread attribute  
  35.         rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);  
  36.         if (rc) {  
  37.             printf("ERROR; return code from pthread_create() is %d\n", rc);  
  38.             exit(-1);  
  39.         }  
  40.     }  
  41.   
  42.     // 4/4: release thread attribute  
  43.     pthread_attr_destroy(&attr);  
  44.   
  45.     void *status;  
  46.     for(t=0; t<NUM_THREADS; t++)  
  47.     {  
  48.         rc = pthread_join(thread[t], &status);  
  49.         if (rc) {  
  50.             printf("ERROR; return code from pthread_join() is %d\n", rc);  
  51.             exit(-1);  
  52.         }  
  53.         printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status);  
  54.     }  
  55.   
  56.     printf("Main: program completed. Exiting.\n");  
  57.     return 0;  
  58. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值