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