#include
#include
HANDLE hSemaphore;
HANDLE h[3];
DWORD WINAPI ThreadProc15(LPVOID lpParam)
{
::WaitForSingleObject(hSemaphore,INFINITE);
printf("线程1正在运行\n");
ReleaseSemaphore(hSemaphore,1,NULL);
return 0;
}
DWORD WINAPI ThreadProc16(LPVOID lpParam)
{
::WaitForSingleObject(hSemaphore,INFINITE);
printf("线程2正在运行\n");
ReleaseSemaphore(hSemaphore,1,NULL);
return 0;
}
DWORD WINAPI ThreadProc17(LPVOID lpParam)
{
::WaitForSingleObject(hSemaphore,INFINITE);
printf("线程3正在运行\n");
ReleaseSemaphore(hSemaphore,1,NULL);
return 0;
}
void CSample08View()
{
hSemaphore=CreateSemaphore(NULL,3,1,NULL);
DWORD uId;
h[0]=::CreateThread(NULL,NULL,ThreadProc15,NULL,NULL,&uId);
h[1]=::CreateThread(NULL,NULL,ThreadProc16,NULL,NULL,&uId);
h[2]=::CreateThread(NULL,NULL,ThreadProc17,NULL,NULL,&uId);
}
int main(int argc,char* argv[])
{
CSample08View();
::WaitForMultipleObjects(3,h,TRUE,INFINITE);
::CloseHandle(h[0]);
::CloseHandle(h[1]);
::CloseHandle(h[2]);
//z这样一来,总算是有点规律可找了,应该是,如果出现123完整的一组,那么就会退出。
return 0;
}
//电脑调用线程是随机的,也就是说代码的执行是不受控制的。