创建Semaphore
hSemaphore = (HANDLE)CreateSemaphoreA(
NULL, //安全属性
0, //最初可使用的资源
10, //最大资源计数
NULL); //命名
hSemaphore = (HANDLE)CreateSemaphoreEx(
PSECURITY_ATTRIBUTES psa, //安全属性
LONG lInintialCount, //最初可使用的资源
LONG lMaxCount, //最大资源计数
PCTSTR pszName, //命名
DWORD dwflags, //系统保留。使用时应为0
DWORD dwDesiredAccess);
打开一个已创建的信号量的句柄
HANDLE OpenSemaphore(
DWORD dwDesiredAccess,
BOOL bInheritHandle,
PCTSTR pszName);
增加信号量的当前计数
BOOL ReleaseSemaphore(
HANDLE hSemaphore,
LONG lRealseCount, //在它是0的时候获得的lPreviousCount也不是当前的计数
//而是上一次释放的量不为0时所得到的值
PLONG plPreviousCount);
代码
各种定义
HANDLE hSemaphore;
HANDLE hThread;
DWORD dwThreadID;
HANDLE hWaitObjects[2];
初始化
BOOL init()
{
hSemaphore = (HANDLE)CreateSemaphoreA(
NULL, //安全属性
0, //最初可使用的资源
10, //最大资源计数
NULL); //命名
hThread = (HANDLE)_beginthreadex(NULL,0,ThreadFunction,NULL,0,(unsigned int*)&dwThreadID);
if(hSemaphore == NULL || hThread == NULL)
{
return FALSE;
}
hWaitObjects[0] = hThread;
hWaitObjects[1] = hSemaphore;
return TRUE;
}
创建线程函数
unsigned __stdcall ThreadFunction(void*)
{
for (int i=0;i<2;++i)
{
printf("Thread %d\n",i+1);
}
return 1;
}
执行操作
int OnActive()
{
if(init())
{
Destory(); //用于关闭句柄
return -1;
}
while (1)
{
LONG lPrevCount;
ReleaseSemaphore(hSemaphore,0,&lPrevCount);
//这里得到的lPrevCount和上一次循环时,下面一段代码中得到的lPrevCount一致,相当于没有进行操作
DWORD dwRet = WaitForMultipleObjects(2,hWaitObjects,FALSE,10);
if (dwRet == WAIT_TIMEOUT)
{
TCHAR chTemp[128];
wsprintf(chTemp,_T("Waited all Timeout ThreadID = %d\n"),dwThreadID);
printf("%S",chTemp);
Sleep(80);
continue;
}
else if (dwRet == WAIT_OBJECT_0)
{
//退出线程
ReleaseSemaphore(hSemaphore,1,&lPrevCount); //要释放的信号量,释放资源的大小,之前的资源大小
printf("Success!Now resource count: %d\n",lPrevCount+1);
Sleep(1000);
if(lPrevCount>=9)
{
Destory();
break;
}
}
else if (dwRet == WAIT_OBJECT_0+1)
{
TCHAR chTemp[128];
wsprintf(chTemp,_T("Waited one result! ThreadID = %d\n"),dwThreadID);
printf("%S",chTemp);
}
else
{
printf("Error is %d!\n",GetLastError());
return -1;
}
}
return 0;
}