1. 程式人生 > >基於互斥物件的執行緒間同步

基於互斥物件的執行緒間同步

<span style="font-size:18px;">#include <iostream>   
#include <windows.h>   
using namespace std;   
 
DWORD WINAPI fun1Proc(LPVOID lpParam);
DWORD WINAPI fun2Proc(LPVOID lpParam);
HANDLE hMutex;
int tickets = 123;//車票的總票數
void main()
{
	HANDLE hThread1,hThread2;
	hThread1 = CreateThread(NULL,0,fun1Proc,NULL,0,NULL);
	hThread2 = CreateThread(NULL,0,fun2Proc,NULL,0,NULL);
	CloseHandle(hThread1);
	CloseHandle(hThread2);
	//hMutex = CreateMutex(NULL,false,NULL);
	hMutex = CreateMutex(NULL,true,NULL);
	WaitForSingleObject(hMutex,INFINITE);
	ReleaseMutex( hMutex);
	ReleaseMutex( hMutex);

	Sleep(4000);

}
DWORD WINAPI fun1Proc(LPVOID lpParam)
{
	while(true)
	{
		WaitForSingleObject(hMutex,INFINITE);
		if(tickets > 0)
		{
			//Sleep(1);
			cout<<"thread1 is selling:"<<tickets--;
			cout<<"\n";
		}
		else break;
		ReleaseMutex(hMutex);
	}

	return 0;
}
DWORD WINAPI fun2Proc(LPVOID lpParam)
{
	while(true)
	{
		WaitForSingleObject(hMutex,INFINITE);
		if(tickets > 0)
		{
			//Sleep(1);
			cout<<"thread2 is selling:"<<tickets--;
			cout<<"\n";
		}
		else break;
		ReleaseMutex(hMutex);
	}

	return 0;
}</span>

注意: