类mutex的原型是:
class mutex;
mutex是一个可锁定的对象, 用于在关键代码部分需要 独占访问 时发出信号, 防止其它线程同时执行和访问相同的内存位置.
mutex提供对对象的独占所有权, 不支持 递归性[即线程不应锁定其已拥有的mutex]. 若要考虑递归性, 请参考 recursive_mutex.
Constructor
default构造函数: constexpr mutex() noexcept;
copy构造函数: mutex (const mutex&) = delete;
因此, mutex对象不能够被 copied / moved.
Lock
函数原型为: void lock()
Calling thread 想lock mutex, 有以下三种情况:
1. 如果mutex 当前没有被 任何thread lock住, then calling thread lock住该mutex (直到mutex.unlock函数被调用, the calling thread 拥有该mutex)
2. 如果mutex 当前被 another thread 拥有 锁住, 则 calling thread被block住, 直到 another thread unlocked 该mutex. (其它non-locked threads则继续它们的执行)
3. 如果mutex 正在被 same thread 通过lock() 函数锁住, 则会产生死锁 (with undefined behavior). 此时, 请参考 recursive_mut