您的位置:首页 > 编程语言 > C语言/C++

C++使用Windows API CreateMutex函数多线程编程

2016-12-28 21:00 267 查看
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;
}

输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: