理解了原理就很好理解
他是在构造函数里面进行了传进去的参数的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;
}