使用信号量机制同步线程

信号量的使用:

信号量的创建:CreateSemaphore(属性指针,初始值,最大值,名称)。

信号量的释放:ReleaseSemaphore(句柄,增加值,原先值指针)。

打开一个信号量:OpenSemaphore(期望的访问权限, 是否继承,名称);



#include <iostream>
#include <Windows.h>

using namespace std;

#define THREAD_INSTANCE_NUMBER 3

DWORD foo(void* pData){
	int threadNumberTemp = *(int *)pData;
	HANDLE hSemaphore;
	cout << "foo: " << threadNumberTemp << " is running" << endl;
	if ((hSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, (LPCWSTR)"Semaphore.Test")) == NULL){
		cout << "open semaphore error." << endl;
	}
	cout << "foo: " << threadNumberTemp << " gets the semaphore" << endl;
	ReleaseSemaphore(hSemaphore, 1, NULL);
	CloseHandle(hSemaphore);
	return 0;
}


int main(){
	DWORD ThreadID[THREAD_INSTANCE_NUMBER];
	HANDLE hThread[THREAD_INSTANCE_NUMBER];
	HANDLE hSemaphore;
	if ((hSemaphore = CreateSemaphore(NULL, 1, 1, (LPCWSTR)"Semaphore.Test")) == NULL){
		cout << "create semaphore error" << endl;
		return 0;
	}

	for (int i = 0; i < THREAD_INSTANCE_NUMBER; i++){
		hThread[i] = CreateThread(NULL,
			0,
			(LPTHREAD_START_ROUTINE)foo,
			(void*)&hThread[i],
			0,
			&(ThreadID[i]));

		if (hThread[i] == NULL){
			cout << "create error: " << ThreadID[i] << endl; 
		}
		else{
			cout << "create thread: " << ThreadID[i] << endl;
		}
		
	}
	WaitForMultipleObjects(THREAD_INSTANCE_NUMBER, hThread, TRUE, INFINITE);
	CloseHandle(hSemaphore);
	return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值