Mutex

Mutex 又称互斥量,如果你要在代码里使用和互斥量相关的变量或者函数,你需要包含头文件​​mutex,std::mutex 是 C++11 中最基本的互斥量,std::mutex 对象提供了独占所有权的特性——即不支持递归地对 std::mutex 对象上锁,而 std::recursive_lock 则可以递归地对互斥量对象上锁。 ​

C++11 中定义了如下与互斥量和锁相关的类:

  • Mutex 系列类(四种),C++11 标准中规定的与互斥量相关的类包括:
  1. ​std::mutex​​,最基本的 Mutex 类,该类提供了最基本的上锁和解锁操作。同时,基本的互斥量不允许某个线程在已获得互斥量的情况下重复对该互斥量进行上锁操作,所以重复上锁将会导致死锁(结果通常未定义的)。std::mutex不允许拷贝构造,也不允许 move 拷贝,最初产生的 mutex 对象是处于 unlocked 状态的。

#include <iostream>       // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
volatile int counter(0); // non-atomic counter
std::mutex mtx; // locks access to counter
void attempt_increases() {
for (int i=0; i<1000; ++i) {
if (mtx.try_lock()) { // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
}
int main (int argc, const char* argv[]) {
std::thread threads[10];
for (int i=0; i<10; ++i)
threads[i] = std::thread(attempt_increases);
for (auto& th : threads) th.join();
std::cout << counter << " successful increases of the counter.\n";
return 0;
}

​std::recursive_mutex​​​,递归 Mutex 类,与 ​​std::mutex​​​ 功能基本相同,但是允许互斥量的拥有者(通常是某个线程)重复对该互斥量进行上锁操作而不会产生死锁,但必须保证上锁和解锁的次数相同.实际上它也是一种可以被上锁的对象,但是和 ​​std::mutex​​​ 不同的是,​​std::recursive_mutex​​​ 允许同一个线程对互斥量多次上锁(即递归上锁),来获得对互斥量对象的多层所有权,​​std::recursive_mutex​​​ 释放互斥量时需要调用与该锁层次深度相同次数的 ​​unlock()​​​,可理解为 ​​lock()​​​ 次数和 ​​unlock()​​​ 次数相同,除此之外,​​std::recursive_mutex​​​ 的特性和 ​​std::mutex​​ 大致相同。


#include <iostream>       // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
class Counter
{
public:
Counter() : count(0) { }
int add(int val) {
std::recursive_mutex::scoped_lock scoped_lock(mutex);
count += val;
return count;
}
int increment() {
std::recursive_mutex::scoped_lock scoped_lock(mutex);
return add(1);
}
private:
boost::recursive_mutex mutex;
int count;
};
Counter c;
void change_count(void*)
{
std::cout << "count == " << c.increment() << std::endl;
}
int main(int, char*[])
{
std::thread threads[10];
for (int i=0; i<10; ++i)
threads[i] = std::thread(change_count, 0);
for (auto& th : threads) th.join();
return 0;
}

  1. ​std::time_mutex​​​,定时 Mutex 类,与 ​​std::mutex​​​ 功能基本相同,但是提供了两个额外的定时上锁操作,​​try_lock_for​​​ 和 ​​try_lock_until​​​,即某个线程在规定的时间内对互斥量进行上锁操作,如果在规定的时间内获得了锁则返回 ​​true​​​, 超时则返回 ​​false​​​,在本章后面的内容中我会介绍​​try_lock_for​​​ 和 ​​try_lock_until​​两个上锁函数之间细微的差异。
  2. ​std::recursive_timed_mutex​​​,定时递归 Mutex 类,既提供了重复上锁功能,又提供了定时上锁的特性(即在规定的时间内没有获得锁则返回 ​​false​​​),相当于 ​​std::recursive_mutex​​​ 和 ​​std::time_mutex​​ 的组合。
  • Lock 类(两种),C++11 标准中定义了两种与互斥量相关的 方式

​std::lock_guard​​,方便线程对互斥量上锁。

​std::unique_lock​​,方便线程对互斥量上锁,但提供了更好的上锁和解锁控制。

#include <iostream>       // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::lock_guard
#include <stdexcept> // std::logic_error
std::mutex mtx;
void print_even (int x) {
if (x%2==0) std::cout << x << " is even\n";
else throw (std::logic_error("not even"));
}
void print_thread_id (int id) {
try {
// using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
std::lock_guard<std::mutex> lck (mtx);
print_even(id);
}
catch (std::logic_error&) {
std::cout << "[exception caught]\n";
}
}


int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_thread_id,i+1);
for (auto& th : threads) th.join();
return 0;
}

后边我将会针对这两种方式分别做阐述说明,两者的区别,优缺点。

  • 其他类型
  1. ​std::once_flag​​​,​​call_once​​ 辅助函数会使用到该类型的对象。
  2. ​std::adopt_lock_t​​​,一个空的标记类,定义如下:​​struct adopt_lock_t {};​​​,该类型的常量对象​​adopt_lock​​​(​​adopt_lock​​​ 是一个常量对象,定义如下:​​constexpr adopt_lock_t adopt_lock {};​​​,​​constexpr​​​ 是 C++11 中的新关键字) 通常作为参数传入给 ​​unique_lock​​​ 或 ​​lock_guard​​ 的构造函数。
  3. ​std::defer_lock_t​​​,一个空的标记类,定义如下:​​struct defer_lock_t {};​​​,该类型的常量对象​​defer_lock​​​(​​defer_lock​​​ 是一个常量对象,定义如下:​​constexpr defer_lock_t defer_lock {};​​​) 通常作为参数传入给 ​​unique_lock​​​ 或 ​​lock_guard​​ 的构造函数。。
  4. ​std::try_to_lock_t​​​,一个空的标记类,定义如下:​​struct try_to_lock_t {};​​​,该类型的常量对象​​try_to_lock​​​(​​try_to_lock​​​ 是一个常量对象,定义如下:​​constexpr try_to_lock_t try_to_lock {};​​​) 通常作为参数传入给 ​​unique_lock​​​ 或 ​​lock_guard​​ 的构造函数。。
  • 辅助函数
  1. ​std::try_lock​​​,尝试同时对多个互斥量上锁。    
    尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会被阻塞。线程调用该函数也会出现下面 3 种情况,
  1. 如果当前互斥量没有被其他线程占有,则该线程锁住互斥量,直到该线程调用 unlock 释放互斥量。
  2. 如果当前互斥量被其他线程锁住,则当前调用线程返回 false,而并不会被阻塞掉。
  3. 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
  1. ​std::lock​​,     同时对多个互斥量上锁。调用线程将锁住该互斥量。线程调用该函数会发生下面 3 种情况:(1). 如果该互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到调用 unlock之前,该线程一直拥有该锁。(2). 如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
  2. ​std::call_once​​​,如果多个线程需要同时调用某个函数,​​call_once​​ 可以保证多个线程对该函数只调用一次。  
  3. unlock(), 解锁,释放对互斥量的所有权。 

#include <iostream>       // std::cout
#include <chrono> // std::chrono::milliseconds
#include <thread> // std::thread
#include <mutex> // std::timed_mutex
std::timed_mutex mtx;
void fireworks() {
// waiting to get a lock: each thread prints "-" every 200ms:
while (!mtx.try_lock_for(std::chrono::milliseconds(200))) {
std::cout << "-";
}
// got a lock! - wait for 1s, then this thread prints "*"
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "*\n";
mtx.unlock();
}




int main () {
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(fireworks);
for (auto& th : threads) th.join();
return 0;
}