1. 程式人生 > >C++使用Windows API CreateMutex函式多執行緒程式設計

C++使用Windows API CreateMutex函式多執行緒程式設計

C++中也可以使用Windows 系統中對應的API函式進行多執行緒程式設計。使用CreateThread函式建立執行緒,並且可以通過CreateMutex建立一個互斥量實現執行緒間資料的同步:

#include <iostream>
#include <Windows.h>

using namespace std;

HANDLE hMutex = NULL; //互斥量

DWORD WINAPI thread01(LPVOID lvParamter)
{
	for (int i = 0; i < 10; i++)
	{
		WaitForSingleObject(hMutex, INFINITE); //互斥鎖
		cout << "Thread 01 is working!" << endl;
		ReleaseMutex(hMutex); //釋放互斥鎖
	}
	return 0;
}

DWORD WINAPI thread02(LPVOID lvParamter)
{
	for (int i = 0; i < 10; i++)
	{
		WaitForSingleObject(hMutex, INFINITE); //互斥鎖
		cout << "Thread 02 is working!" << endl;
		ReleaseMutex(hMutex); //釋放互斥鎖
	}
	return 0;
}


int main()
{
	hMutex = CreateMutex(NULL, FALSE, (LPCWSTR)"Test"); //建立互斥量
	HANDLE hThread = CreateThread(NULL, 0, thread01, NULL, 0, NULL);  //建立執行緒01
	hThread = CreateThread(NULL, 0, thread02, NULL, 0, NULL);     //建立執行緒01
	CloseHandle(hThread); //關閉控制代碼
	system("pause");
	return 0;
}

輸出: