創建兩個線程模擬火車站兩個窗口售票程序

#include <Windows.h>
#include <iostream>
using namespace std;

DWORD WINAPI Fun1(LPVOID lpParameter);

DWORD WINAPI Fun2(LPVOID lpParameter);


int index = 0;
int tickets = 100;  
HANDLE hMutex;
int main()
{
 HANDLE hThread1;
 HANDLE hThread2;

 hThread1 = CreateThread(NULL,0,Fun1,NULL,0,NULL);
 hThread2 = CreateThread(NULL,0,Fun2,NULL,0,NULL);
 CloseHandle(hThread1);  
 CloseHandle(hThread2);

 hMutex=CreateMutex(NULL, FALSE, "tickets");//申請一個名爲tickets的互斥資源且不屬於當前線程
 //WaitForSingleObject(hMutex, INFINITE);
 //ReleaseMutex(hMutex);

//或
/*  hMutex=CreateMutex(NULL, TRUE, "tickets");<span style="font-family: Arial, Helvetica, sans-serif;">//申請一個名爲tickets的互斥資源且屬於當前線程,要釋放後該互斥資源,其他線程才能用</span>
 WaitForSingleObject(hMutex, INFINITE);
 ReleaseMutex(hMutex);
 ReleaseMutex(hMutex); */
 Sleep(400000); //主線程掛起400秒,先去執行子線程
 return 0;
}

DWORD WINAPI Fun1(LPVOID lpParameter)
{
 while (TRUE)
 {
  ReleaseMutex(hMutex);
  WaitForSingleObject(hMutex, INFINITE);
  if (tickets > 0)
  {
   Sleep(1000);
   cout<<"thread1 sell ticket : "<<tickets--<<endl;
  }
  else
  {
   break;
  }
  ReleaseMutex(hMutex);
 }
 return 0;
}


DWORD WINAPI Fun2(LPVOID lpParameter)
{
 while (TRUE)
 {
  ReleaseMutex(hMutex);
  WaitForSingleObject(hMutex, INFINITE);
  if (tickets > 0)
  {
   Sleep(1000);
   cout<<"thread2 sell ticket : "<<tickets--<<endl;
  }
  else
  {
   break;
  }
  ReleaseMutex(hMutex);
 }
 return 0;
}

發佈了4 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章