多线程4 mutex

#include "stdafx.h"
#include <windows.h>
#include "iostream"

using namespace std;
int index = 0;
int tickets = 100;

HANDLE hMutex;

DWORD WINAPI func1(LPVOID lpParameter)
{
 while(true)
 {
  WaitForSingleObject(hMutex,INFINITE);
  if(tickets>0)
  {
   Sleep(1);
      cout<<"Thread1 sells ticket"<<tickets--<<endl;
  }
  else
   break;
  ReleaseMutex(hMutex);

 }
 return 0;
}

DWORD WINAPI func2(LPVOID lpParemteter)
{
 while(true)
 {
  WaitForSingleObject(hMutex,INFINITE);
  if(tickets>0)
  {
   Sleep(1);
   cout<<"Thread2 sells ticket"<<tickets--<<endl;
  }
  else
   break;
 }
 return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
 hMutex = CreateMutex(NULL,false,NULL);
 HANDLE hThread1 = CreateThread(NULL,0,func1,NULL,0,NULL);
 HANDLE hThread2 = CreateThread(NULL,0,func2,NULL,0,NULL);
 CloseHandle(hThread1);
 CloseHandle(hThread2);
 Sleep(4000); `
 return 0;
}

你可能感兴趣的:(多线程,职场,mutex,休闲)