使用std::mutex创建互斥量,通过调用成员函数lock()进行上锁,unlock()进行解锁。但不方便的是需要记住锁后要在函数出口再次调用unlock()解锁.
因此可以用std::lock_guard,其会在构造的时候提供已锁的互斥量,并在析构的时候进行解锁,从而保证自动管理。
代码示例。
#include <list>
#include <mutex>
#include <algorithm>
std::list<int> some_list; // 1
std::mutex some_mutex; // 2
void add_to_list(int new_value)
{
std::lock_guard<std::mutex> guard(some_mutex); // 3
some_list.push_back(new_value);
}
bool list_contains(int value_to_find)
{
std::lock_guard<std::mutex> guard(some_mutex); // 4
return std::find(some_list.begin(),some_list.end(),value_to_find) != some_list.end();
}
当然,也不是总是那么理想,聪明的你一定注意到了:当其中一个成员函数返回的是保护数据的指针或引用时,会破坏对数据的保护。具有访问能力的指针或引用可以访问(并可能修改)被保护的数据,而不会被互斥锁限制。互斥量保护的数据需要对接口的设计相当谨慎,要确保互斥量能锁住任何对保护数据的访问,并且不留后门。
本文代码例子解释摘自《
c++并发编程》 在线阅读链接:https://chenxiaowei.gitbooks.io/cpp_concurrency_in_action/content/content/chapter3/chapter3-chinese.html