Windows多线程示例代码

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

运行结果如图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值