#include <stdio.h>
#include <windows.h>
int number = 1;
HANDLE hDemaphore;
unsigned long __stdcall ThreadProc1(void* lpParameter)
{
long count;
while(number<100)
{
WaitForSingleObject(hDemaphore,INFINITE);
printf("线程1当前计数: %d\n",number);
number++;
Sleep(100);
ReleaseSemaphore(hDemaphore,1,&count);
}
return 0;
}
unsigned long __stdcall ThreadProc2(void *lpParameter)
{
long count;
while(number<100)
{
WaitForSingleObject(hDemaphore,INFINITE);
printf("线程2当前计数: %d\n",number);
number++;
Sleep(100);
ReleaseSemaphore(hDemaphore,1,&count);
}
return 0;
}
int main()
{
HANDLE hThread1 = CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
HANDLE hThread2 = CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
hDemaphore = CreateSemaphore(NULL,1,100,"sem");
CloseHandle(hThread1);
CloseHandle(hThread2);
while(1)
{
;
}
return 0;
}