#include <windows.h>
#include <iostream>
using namespace std;
#define Max_Sem_Count 10
#define ThreadCount 12
HANDLE ghSemphores;
DWORD WINAPI ThreadFunc(LPVOID);
int main()
{
HANDLE Thread[ThreadCount];
DWORD ThreadID;
ghSemphores=CreateSemaphore(NULL,Max_Sem_Count,Max_Sem_Count,NULL);
if (ghSemphores==NULL)
{
cout<<"Create Semaphore Error"<<endl;
return 1;
}
for (int i=0;i<ThreadCount;i++)
{
Thread[i]=CreateThread(NULL,0,ThreadFunc,NULL,0,&ThreadID);
if (Thread[i]==NULL)
{
cout<<"Create Thread Failed"<<endl;
return 1;
}
}
WaitForMultipleObjects(ThreadCount,Thread,TRUE,INFINITE);
for (i=0;i<ThreadCount;i++)
{
CloseHandle(Thread[i]);
}
return 0;
}
DWORD WINAPI ThreadFunc(LPVOID lpParam)
{
UNREFERENCED_PARAMETER(lpParam);
DWORD dwWaitResult;
BOOL bContinue=TRUE;
while(bContinue)
{
dwWaitResult=WaitForSingleObject(ghSemphores,0L);
switch(dwWaitResult)
{
case WAIT_OBJECT_0:
{
cout<<"Thread"<<GetCurrentThreadId()<<"has Waited Successful"<<endl;
bContinue=FALSE;
::Sleep(5);
if (!ReleaseSemaphore(ghSemphores,1,NULL))
{
cout<<"Release Semaphore Failed!"<<endl;
}
}
break;
case WAIT_TIMEOUT:
cout<<"Thread"<<GetCurrentThreadId()<<"has Waited Failed"<<endl;
break;
}
}
return 0;
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。