多線程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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章