C++多線程同步(采用互斥對象Mutex)
// Mutex.cpp : 定義控制台應用程式的入口點。
//
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI Proc1(LPVOID lpParameter);//線程1的入口函數
DWORD WINAPI Proc2(LPVOID lpParameter);//線程2的入口函數
int ticket = 100;
HANDLE hMutex;//全局互斥對象
void main()
{
HANDLE hthread1;
HANDLE hthread2;
//建立線程
hthread1 = CreateThread(NULL,0,Proc1,NULL,0,NULL);
hthread2 = CreateThread(NULL,0,Proc2,NULL,0,NULL);
CloseHandle(hthread1);//并沒有終止線程的運作;當不再需要線程句柄時,應将其關閉,讓這個線程核心對象的引用計數減1
CloseHandle(hthread2);
//建立互斥對象
hMutex = CreateMutex(NULL,FALSE,NULL);
//保證應用程式隻有一個執行個體
if (hMutex)
{
if (ERROR_ALREADY_EXISTS == GetLastError())
{
cout<<"隻有一個執行個體可以運作!"<<endl;
return;
}
}
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Sleep(4000);//主線程靜默4秒
}
DWORD WINAPI Proc1(
LPVOID lpParameter)
{
while (TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
Sleep(1);
if (ticket > 0)
cout<<"thread1 sell ticket: "<<ticket--<<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Proc2(
LPVOID lpParameter)
{
while (TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
Sleep(1);
if (ticket > 0)
cout<<"thread2 sell ticket: "<<ticket--<<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
}