#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<math.h>
#include <Windows.h>
DWORD WINAPI Fun1(LPVOID lpParameter);
DWORD WINAPI Fun2(LPVOID lpParameter);
HANDLE hTicketMutex;//保存互斥对象的句柄
int tickets = 20;
int main(void)
{
HANDLE hThread1,hThread2;
hTicketMutex = CreateMutex(NULL, FALSE, "ticket");
hThread1= CreateThread(NULL, 0, Fun1, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Fun2, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
Sleep(4000);
system("pause");
return 0;
}
DWORD WINAPI Fun1(LPVOID lpParameter)
{
while (tickets > 0)
{
WaitForSingleObject(hTicketMutex, INFINITE);
if(tickets>0)
printf("thread1 sell ticket:%d\n", tickets--);
ReleaseMutex(hTicketMutex);
}
return 0;
}
DWORD WINAPI Fun2(LPVOID lpParameter)
{
while (tickets > 0)
{
WaitForSingleObject(hTicketMutex, INFINITE);
if(tickets>0)
printf("thread2 sell ticket:%d\n", tickets--);
ReleaseMutex(hTicketMutex);
}
return 0;
}
用devc跑的,这次没用vs2017