多線程示例代碼

#include "stdafx.h"

void* thread1(void* arg);		// 線程函數
void* thread2(void* arg);
void* thread3(void* arg);

pthread_mutex_t			gLock;	// 線程鎖
pthread_cond_t			gCond;	// 條件變量
volatile bool			gStop;	// 運行狀態
int				gArg;	// 線程參數

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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章