lock_guard<mutex> name(mutex param)的坑点

理解了原理就很好理解
他是在构造函数里面进行了传进去的参数的lock
在析构函数里面进行了传进去参数的unlock
所以有的时候使用lock_guard竟发现是全部同步的,一个全部执完,另一个在开始执行,这背离了我们的初衷
主要原因就是要看好lock_guard的作用域,不退出作用域,他一直不销毁,这才出现了一个全部执行玩,再执行另一个的效果。
如下面的例子,要是把addMethod , exMethod分别放入addMoveActions , executeMoveAction函数里面,再函数开始的时候声明lock_guard,就会出现这种效果

#include <iostream>
#include <thread>
#include <list>
#include <mutex>
using namespace std;

class AClass
{
private:
	list<int> moveAction;
	mutex myLock;
public:

	void addMethod(int i)
	{
		lock_guard<mutex> sbLockGuard(myLock);
		//myLock.lock();
		moveAction.push_back(i);
		//myLock.unlock();
	}

	void addMoveActions()
	{
		for (int i = 0; i < 1000; ++i)
		{ 
			addMethod(i);
			cout << "线程:" << this_thread::get_id() << " === " << "接收action参数:" << i << endl;
		}
	}

	void exMethod()
	{
		lock_guard<mutex> sbLockGuard(myLock);

		int action = moveAction.front();
		moveAction.pop_front();
		//myLock.unlock();
		cout << "线程:" << this_thread::get_id() << " === " << "执行action参数:" << action << endl;

	}

	void executeMoveAction()
	{
		
		for (int i = 0; i < 1000; ++i)
		{	
			if (!moveAction.empty())
			{
				exMethod();
			}
			else {
				cout << "没有行动" << endl;
			}
		}
	}
};

int main()
{
	AClass abc;
	thread myReceiveActionThread(&AClass::addMoveActions, &abc);
	thread myExecuteActionThread(&AClass::executeMoveAction, &abc);
	//thread myExecuteActionThread2(&AClass::executeMoveAction, &abc);
	//thread myExecuteActionThread3(&AClass::executeMoveAction, &abc);
	//thread myExecuteActionThread4(&AClass::executeMoveAction, &abc);
	//thread myExecuteActionThread5(&AClass::executeMoveAction, &abc);
	myExecuteActionThread.join();
	//myExecuteActionThread2.join();
	//myExecuteActionThread3.join();
	//myExecuteActionThread4.join();
	//myExecuteActionThread5.join();
	myReceiveActionThread.join();
	cout << "主线程执行完毕" << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值