// thread.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <vector>
#include <iostream>
#include <process.h>
using namespace std;
// 线程函数
unsigned int __stdcall thread1(LPVOID arg);
unsigned int __stdcall thread2(LPVOID arg);
HANDLE gMutex; // 线程锁
volatile bool gStop; // 结束状态
vector<int> gVecNumbers; // 数组
int gArgs; // 线程参数
#define NUMBERS 8
int _tmain(int argc, _TCHAR* argv[])
{
gMutex = CreateMutex(NULL, FALSE, "ThreadMutex"); // 创建互斥体
gStop = false;
HANDLE hThread = 0;
unsigned int nThreadId = 0;
vector<HANDLE> vecHandles;
vector<unsigned (__stdcall*)(void *)> vecFuns;
// 添加多个线程函数
vecFuns.push_back(thread1);
vecFuns.push_back(thread2);
// 创建多个线程
for (unsigned int i = 0; i < vecFuns.size(); i++)
{
WaitForSingleObject(gMutex, INFINITE);
hThread = (HANDLE)_beginthreadex(NULL, 0, vecFuns[i], (void*)&gArgs,
CREATE_SUSPENDED, &nThreadId);
ResumeThread(hThread);
vecHandles.push_back(hThread);
ReleaseMutex(gMutex);
}
// 等待线程结束
for (unsigned int i = 0; i < vecHandles.size(); i++)
{
WaitForSingleObject(vecHandles[i], INFINITE);
}
getchar();
return 0;
}
unsigned int __stdcall thread1(LPVOID arg)
{
// 线程1向vector里添加数据,添加完成后设置gStop为true
for (int i = 0; i < NUMBERS; i++)
{
WaitForSingleObject(gMutex, INFINITE);
gVecNumbers.push_back(i);
cout << "thread 1 add " << i << endl;
if (i == NUMBERS - 1)
gStop = true;
ReleaseMutex(gMutex);
}
return 0;
}
unsigned int __stdcall thread2(LPVOID arg)
{
// 线程2从vector里删除数据
while (!gStop)
{
WaitForSingleObject(gMutex, INFINITE);
if (gVecNumbers.size() > 0)
{
cout << " thread 2 remove " << *gVecNumbers.begin() << endl;
gVecNumbers.erase(gVecNumbers.begin());
}
ReleaseMutex(gMutex);
}
return 0;
}
运行结果如图: