Linux POSIX线程实现wait_group功能
来源:互联网 发布:传奇世界怪物数据库 编辑:程序博客网 时间:2024/05/29 18:35
Linux POSIX线程实现wait_group功能
wait_group:
用一个数据结构实现让主线程等待一组线程执行结束之后在退出的功能。
方法:
方法一:
主线程调用pthread_exit((void *)2);
原因:
- pthread_exit在main中有只终止main线程,而不终止整个进程的作用(注意不存在父子线程的概念)
- 在main线程终止时如果调用了pthread_exit(),那么此时终止的只是main线程,而进程的资源会为其他由main线程创建的线程保持打开的状态,直到其他线程都终止。而在其他的由main线程创建的线程中pthread_exit并没有这种作用。
方法二:
主线程对于各个线程调用pthread_join()
pthread_join(t3,NULL);pthread_join(t2,NULL);pthread_join(t1,NULL);
注意:即使t1比t2和t3先退出也没有关系
方法三:
模拟golang中的wait_group功能,利用条件变量实现相同功能。
#include <cstdlib>#include <iostream>#include <string>#include <algorithm> #include <pthread.h>#include <sys/time.h>#include <unistd.h>using namespace std;struct wait_group { /*要等待退出的线程数*/ int count; /*保证存取操作的原子性 互斥性*/ pthread_mutex_t locker; /*是否组内线程都完成了*/ pthread_cond_t all_done; wait_group(int val) : count(val) { pthread_mutex_init(&locker, NULL); pthread_cond_init(&all_done, NULL); } /*增加要等待的线程数量,如果val为负数则是减少*/ void add(int val) { pthread_mutex_lock(&locker); count += val; if (count < 0) { cout << "error, count is a negative value" << endl; } else if (count > 0) { ; } else { cout << "send signal" << endl; pthread_cond_signal(&all_done); } pthread_mutex_unlock(&locker); } /*线程执行完毕之后调用*/ void done() { add(-1); } /*主线程调用wait阻塞在这里,直到所有的线程都运行完成*/ void wait() { pthread_mutex_lock(&locker); while (count != 0) { pthread_cond_wait(&all_done, &locker); } pthread_mutex_unlock(&locker); }};struct wait_group wp(3);void* tprocess1(void* args) { sleep(3); cout << "tprocess1" << endl; wp.done(); return NULL;}void* tprocess2(void* args) { sleep(2); cout << "tprocess2" << endl; wp.done(); return NULL;}void* tprocess3(void* args) { sleep(1); cout << "tprocess3" << endl; wp.done(); return NULL;}int main(int argc, char** argv) { pthread_t t1; pthread_t t2; pthread_t t3; pthread_create(&t1, NULL, tprocess1, NULL); pthread_create(&t2, NULL, tprocess2, NULL); pthread_create(&t3, NULL, tprocess3, NULL); wp.wait(); return 0;}
阅读全文
0 0
- Linux POSIX线程实现wait_group功能
- POSIX 线程取消点的 Linux 实现
- POSIX 线程取消点的 Linux 实现
- POSIX 线程取消点的 Linux 实现
- POSIX 线程取消点的 Linux 实现
- Linux POSIX线程详解
- linux程序设计:POSIX线程
- 利用POSIX文件函数部分实现linux中的cp功能
- POSIX 线程取消点的 Linux 实现(zz)
- Linux上posix线程库实现原理讨论
- Linux上posix线程库实现原理讨论 .
- linux的线程(posix thread)
- Linux Programing -- ch12-- POSIX 线程
- linux thread model . Linux上posix线程库实现原理讨论
- 本地POSIX线程库(NPTL)(经典,说明了真实linux系统的实现)
- 收藏.Linux.Posix线程编程指南
- Linux程序设计读书笔记——POSIX线程
- linux Posix线程同步(条件变量) 实例
- Qt 采集音频
- 菜鸟JAVA路
- MySql_5.7解压版本安装心得
- BZOJ 1531: [POI2005]Bank notes 多重背包
- Windows10操作系统下hosts文件的修改和常见问题
- Linux POSIX线程实现wait_group功能
- HDU
- 控制寄存器(CR0,CR1,CR2,CR3,CR4)
- U盘启动盘制作及win8系统重装
- MFC CString分割文本
- 学习笔记---getAttribute与setAttribute 的用法
- IIS(或汤姆猫)+PHP+MySQL+帝国cms的搭建
- 事件的取消
- Spring Cloud Security