关闭

使用信号量机制同步线程

284人阅读 评论(0) 收藏 举报
分类:

信号量的使用:

信号量的创建: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;
}








0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:38156次
    • 积分:2641
    • 等级:
    • 排名:第14242名
    • 原创:241篇
    • 转载:4篇
    • 译文:0篇
    • 评论:0条