c/c++: 多线程编程基础讲解(四)

经过前面的几个例子,是不是还少个线程创建时属性参数没有提到,见下文示例:

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <pthread.h>  
  3.   
  4.   
  5. #include <iostream>  
  6. #include <pthread.h>  
  7.   
  8. using namespace std;  
  9.   
  10. #define NUM_THREADS 5  
  11.   
  12. void* say_hello(void* args)  
  13. {  
  14.     cout << "hello in thread " << *((int *)args) << endl;  
  15.     int status = 10 + *((int *)args);//将参数加10  
  16.     pthread_exit((void*)status);//由于线程创建时候提供了joinable参数,这里可以在退出时添加退出的信息:status供主程序提取该线程的结束信息;  
  17. }  
  18.   
  19. int main()  
  20. {  
  21.     pthread_t tids[NUM_THREADS];  
  22.     int indexes[NUM_THREADS];  
  23.   
  24.     pthread_attr_t attr;//要想创建时加入参数,先声明  
  25.     pthread_attr_init(&attr);//再初始化  
  26.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);//声明、初始化后第三步就是设置你想要指定线程属性参数,这个参数表明这个线程是可以join连接的,join功能表示主程序可以等线程结束后再去做某事,实现了主程序和线程同步功能,这个深层理解必须通过图示才能解释;参阅其他资料吧  
  27.   
  28.     for(int i = 0; i < NUM_THREADS; ++i)  
  29.     {  
  30.         indexes[i] = i;  
  31.         int ret = pthread_create( &tids[i], &attr, say_hello, (void *)&(indexes[i]) );//这里四个参数都齐全了,更多的配置仍需查阅资料;  
  32.         if (ret != 0)  
  33.         {  
  34.            cout << "pthread_create error: error_code=" << ret << endl;  
  35.         }  
  36.     }  
  37.   
  38.     pthread_attr_destroy(&attr);//参数使用完了就可以销毁了,必须销毁哦,防止内存泄露;  
  39.   
  40.     void *status;  
  41.     for (int i = 0; i < NUM_THREADS; ++i)  
  42.     {  
  43.         int ret = pthread_join(tids[i], &status);//前面创建了线程,这里主程序想要join每个线程后取得每个线程的退出信息status;  
  44.         if (ret != 0)  
  45.         {  
  46.             cout << "pthread_join error: error_code=" << ret << endl;  
  47.         }  
  48.         else  
  49.         {  
  50.             cout << "pthread_join get status: " << (long)status << endl;  
  51.         }  
  52.     }  
  53. }  

编译运行 g++ -lpthread -o ex_join ex_join.cpp

结果:

[plain]  view plain copy
  1. hello in thread 4  
  2. hello in thread 3  
  3. hello in thread 2  
  4. hello in thread 1  
  5. hello in thread 0  
  6. pthread_join get status: 10  
  7. pthread_join get status: 11  
  8. pthread_join get status: 12  
  9. pthread_join get status: 13  
  10. pthread_join get status: 14  

体会一下join的功能吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值