windows 信号量使用
#include<iostream>
#include <Windows.h>
using namespace std;
const int MAX_SEM_COUNT = 5;//信号量数量
const int THREAD_COUNT = 10;//线程数量
HANDLE g_sem;//全局信号量对象句柄
DWORD WINAPI threadFunc(LPVOID);//线程函数前向声明
int main()
{
HANDLE arrThread[THREAD_COUNT];
g_sem = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);
if (!g_sem)
{
cout<<"call CreateSemaphore() failed!"<<endl;
return -1;
}
DWORD threadID = -1;
for (int i = 0; i < THREAD_COUNT; ++i)
{
arrThread[i] = CreateThread(NULL, 0, threadFunc, NULL, 0, &threadID);
if (!arrThread[i])
{
cout<<"call CreateThread() failed!"<<endl;
return -2;
}
}
WaitForMultipleObjects(THREAD_COUNT, arrThread, true, INFINITE);
for (int i = 0; i < THREAD_COUNT; ++i)
{
CloseHandle(arrThread[i]);
}
CloseHandle(g_sem);
system("pause");
return 0;
}
//线程函数,使用信号量的例子
DWORD WINAPI threadFunc(LPVOID)
{
DWORD waitResult;
bool bContinue = true;
while (bContinue)
{
waitResult = WaitForSingleObject(g_sem,0);
switch (waitResult)
{
case WAIT_OBJECT_0:
cout << GetCurrentThreadId()<< " wait sem succeed!"<< endl;
bContinue = false;
Sleep(5);
if (!ReleaseSemaphore(g_sem, 1, NULL))
{
cout<<"call ReleaseSemaphore() failed!"<<endl;
return GetLastError();
}
break;
case WAIT_TIMEOUT:
cout << GetCurrentThreadId()<< " wait sem timeout!"<< endl;
break;
}
}
}