C++ 多线程编程 互斥量

Win10下多线程中访问公共变量时,可使用mutex类来做,头文件为mutex,实例(VS2013):

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

using namespace std;

mutex mu;  //线程互斥对象

int totalNum = 100;

void thread01()
{
	while (totalNum > 0)
	{
		mu.lock(); //同步数据锁
		cout << totalNum << endl;
		totalNum--;
		Sleep(100);
		mu.unlock();  //解除锁定
	}
}
void thread02()
{
	while (totalNum > 0)
	{
		mu.lock();
		cout << totalNum << endl;
		totalNum--;
		Sleep(100);
		mu.unlock();
	}
}

int main()
{
	thread task01(thread01);
	thread task02(thread02);
	task01.detach();
	task02.detach();
	system("pause");
}


输出:



若不加互斥,如下屏蔽:

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

using namespace std;

mutex mu;  //线程互斥对象

int totalNum = 100;

void thread01()
{
	while (totalNum > 0)
	{
	//	mu.lock(); //同步数据锁
		cout << totalNum << endl;
		totalNum--;
		Sleep(100);
	//	mu.unlock();  //解除锁定
	}
}
void thread02()
{
	while (totalNum > 0)
	{
	//	mu.lock();
		cout << totalNum << endl;
		totalNum--;
		Sleep(100);
	//	mu.unlock();
	}
}

int main()
{
	thread task01(thread01);
	thread task02(thread02);
	task01.detach();
	task02.detach();
	system("pause");
}


可看到,有丢失,有重复的现象出现:



参考网址


还可使用如下方法,用WaitForSingleObject和ReleaseMutex:

#include <iostream>   
#include <windows.h>   
using namespace std;
DWORD bRet;
HANDLE hMutex = NULL;
DWORD WINAPI Fun(LPVOID lpParamter)
{
	for (int i = 0; i < 10; i++)
	{
		bRet = WaitForSingleObject(hMutex, INFINITE);
		if (bRet == WAIT_OBJECT_0)
		{
	//		printf("Process is signaled...:%d\n", GetLastError());
		}
		else if (bRet == WAIT_TIMEOUT)
		{
	//		printf("Time out...:%d\n", GetLastError());
		}
		else if (bRet == WAIT_FAILED)
		{
	//		printf("Invalid process handle...:%d\n", GetLastError());
		}
		cout << "A    Thread Display!" << endl;
		ReleaseMutex(hMutex);
		Sleep(100);
	}
	return 0L;
}

int main()
{
	hMutex = CreateMutex(NULL, FALSE, NULL);
	HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
	CloseHandle(hThread);
	for (int i = 0; i < 10; i++)
	{
		WaitForSingleObject(hMutex, INFINITE);
		cout << "Main Thread Display!" << endl;
		ReleaseMutex(hMutex);
		Sleep(200);
	}
	system("PAUSE");
	return 0;
}

结果:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值