使用scoped_lock避免死锁

时间:2018-04-17 18:32:18

标签: c++ c++17

我正在测试Galowicz C ++ 17书中的一些示例代码,如下所示:

#include <iostream>
#include <mutex>
#include <thread>

using namespace std;
using namespace chrono_literals;

mutex mut_a;
mutex mut_b;

static void deadlock_func_1() {
  cout << "bad f1 acquiring mutex A..." << endl;
  lock_guard<mutex> la{mut_a};
  this_thread::sleep_for(100ms);
  cout << "bad f1 acquiring mutex B..." << endl;
  lock_guard<mutex> lb{mut_b};
  cout << "bad f1 got both mutexes." << endl;
}
static void deadlock_func_2() {
  cout << "bad f2 acquiring mutex B..." << endl;
  lock_guard<mutex> lb{mut_b};
  this_thread::sleep_for(100ms);
  cout << "bad f2 acquiring mutex A..." << endl;
  lock_guard<mutex> la{mut_a};
  cout << "bad f2 got both mutexes." << endl;
}

static void sane_func_1() {
  scoped_lock l{mut_a, mut_b};
  cout << "sane f1 got both mutexes.:" << endl;
}
static void sane_func_2() {
  scoped_lock l{mut_b, mut_a};
  cout << "sane f2 got both mutexes." << endl;
}

int main() {
  {
    thread t1{sane_func_1};
    thread t2{sane_func_2};
    t1.join();
    t2.join();
  }
}

我在scoped_locksane_func_1()内的sane_func_2()行上收到了E0441,C2955和C2514错误。编译器抱怨这两行的参数列表和构造函数。我希望它只是一个我忽略的语法错误,或者是一些超出适当范围的错误。

0 个答案:

没有答案