多线程示例代码

来源:互联网 发布:淘宝未收到货显示签收 编辑:程序博客网 时间:2024/06/06 12:52
#include "stdafx.h"void* thread1(void* arg);// 线程函数void* thread2(void* arg);void* thread3(void* arg);pthread_mutex_tgLock;// 线程锁pthread_cond_tgCond;// 条件变量volatile boolgStop;// 运行状态intgArg;// 线程参数int _tmain(int argc, _TCHAR* argv[]){pthread_t pt;vector<pthread_t> vecIDs;vector<void* (*)(void*)> vecFuns;vecFuns.push_back(thread1);vecFuns.push_back(thread2);vecFuns.push_back(thread3);// 创建多个线程for (unsigned int i = 0; i < vecFuns.size(); i++){pthread_mutex_lock(&gLock);pthread_create(&pt, NULL, vecFuns[i], (void*)gArg);vecIDs.push_back(pt);pthread_cond_wait(&gCond, &gLock);pthread_mutex_unlock(&gLock);}// 等待线程结束int nResult = 0;for (unsigned int i = 0; i < vecFuns.size(); i++){pthread_join(vecIDs[i], (void**)nResult);}return 0;}

原创粉丝点击