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;
}
输出: