#include<iostream>
#include<windows.h>
#include<process.h>
#define max 10
using namespace std;
CRITICAL_SECTION cs;
HANDLE hHandle; //Semaphore handle
int semanum;
unsigned int _stdcall ThreadFunc(LPVOID lpa)
{
int k = *(int *)lpa;
ReleaseSemaphore(hHandle, 1, NULL);
Sleep(500);
EnterCriticalSection(&cs);
semanum++;
Sleep(100);
cout << "Thread ID Is " <<k << ", num = " << semanum << endl;
LeaveCriticalSection(&cs);
return 0;
}
int main()
{
hHandle = CreateSemaphore(NULL, 0, 1, NULL);
InitializeCriticalSection(&cs);
HANDLE Handle[max] = { 0 };
int i = 0;
semanum = 0;
while (i<max)
{
Handle[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc, &i, 0, 0);
WaitForSingleObject(hHandle, INFINITE);
i++;
}
WaitForMultipleObjects(10, Handle, TRUE, INFINITE);
CloseHandle(hHandle);
for (int j = 0; j<10; j++)
{
CloseHandle(Handle[j]);
}
DeleteCriticalSection(&cs);
cout << "Program End!!" << endl;
system("pause");
return 0;
}
CreateSemaphore参数:
<div class="para" label-module="para">lpSemaphoreAttributes SECURITY_ATTRIBUTES,指定一个SECURITY_ATTRIBUTES结构,或传递零值(将参数声明为ByVal As Long,并传递零值)——表示采用不允许继承的默认描述符。该参数定义了<a target=_blank href="http://baike.baidu.com/view/1303265.htm" target="_blank">信号量</a>的安全特性</div><div class="para" label-module="para">lInitialCount Long,设置信号量的初始计数。可设置零到lMaximumCount之间的一个值</div><div class="para" label-module="para">lMaximumCount Long,设置信号量的最大计数</div><div class="para" label-module="para">lpName String,指定信号量对象的名称。用vbNullString可创建一个<a target=_blank href="http://baike.baidu.com/view/1418045.htm" target="_blank">未命名</a>的<a target=_blank href="http://baike.baidu.com/view/1303265.htm" target="_blank">信号量</a>对象。如果已经存在拥有这个名字的一个信号量,就直接打开现成的信号量。这个名字可能不与一个现有的<a target=_blank href="http://baike.baidu.com/view/3074680.htm" target="_blank">互斥体</a>、事件、可等待<a target=_blank href="http://baike.baidu.com/view/928508.htm" target="_blank">计时器</a>或文件映射的名称相符</div>
通常第一个和第四个都设为0