#include "stdafx.h" #include <windows.h> #include <process.h> using namespace std; HANDLE hSemaphoreA; HANDLE hSemaphoreB; HANDLE hSemaphoreC; int num=0; unsigned int __stdcall FunA(LPVOID p) { while(num<99) { WaitForSingleObject(hSemaphoreA,INFINITE); printf("A:%d ",num); num++; ReleaseSemaphore(hSemaphoreB,1,NULL); } return 0; } unsigned int __stdcall FunB(LPVOID p) { while(num<99) { WaitForSingleObject(hSemaphoreB,INFINITE); printf("B:%d ",num); num++; ReleaseSemaphore(hSemaphoreC,1,NULL); } return 0; } unsigned int __stdcall FunC(LPVOID p) { while(num<99) { WaitForSingleObject(hSemaphoreC,INFINITE); printf("C:%d ",num); num++; ReleaseSemaphore(hSemaphoreA,1,NULL); } return 0; } void main() { HANDLE hThread[3]; hSemaphoreA=CreateSemaphore(NULL,1,1,NULL); hSemaphoreB=CreateSemaphore(NULL,0,1,NULL); hSemaphoreC=CreateSemaphore(NULL,0,1,NULL); hThread[0]=(HANDLE)_beginthreadex(NULL,0,FunA,NULL,0,0); hThread[1]=(HANDLE)_beginthreadex(NULL,0,FunB,NULL,0,0); hThread[2]=(HANDLE)_beginthreadex(NULL,0,FunC,NULL,0,0); WaitForMultipleObjects(3,hThread,TRUE,INFINITE); for(int i=0;i<3;i++) { CloseHandle(hThread[i]); } CloseHandle(hSemaphoreA); CloseHandle(hSemaphoreB); CloseHandle(hSemaphoreC); }