首页 > 解决方案 > 在持有互斥锁的同时调用 notify_one()/notify_all() 是不好的做法吗?

问题描述

我正在编写一个练习程序来理解 C++ 中的多线程概念。该程序只是在一个线程上读取用户输入的字符串,然后在另一个线程中处理它。

1   #include <iostream>
2   #include <thread>
3   #include <condition_variable>
4   #include <mutex>
5   #include <queue>
6   #include <string>
7   
8   #define __DEBUG
9   
10  #ifdef __DEBUG
11  #define PRINT cout << __FUNCTION__ << " --- LINE : " << __LINE__ << '\n'
12  #else
13  #define PRINT
14  #endif
15  
16  using namespace std;
17  
18  condition_variable g_CondVar;
19  mutex g_Mutex;
20  queue<string> g_Queue;
21  
22  void AddTaskToQueue()
23  {
24      string InputStr;
25      while (true)
26      {
27          lock_guard<mutex> LG(g_Mutex);
28          PRINT;
29          cin >> InputStr;
30          PRINT;
31          g_Queue.push(InputStr);
32          PRINT;
33          g_CondVar.notify_one();
34          PRINT;
35          if (InputStr == "Exit")
36              break;
37          this_thread::sleep_for(50ms);
38      }
39  }
40  
41  void ProcessQueue()
42  {
43      PRINT;
44      unique_lock<mutex> UL(g_Mutex);
45      PRINT;
46      string ProcessingStr;
47      PRINT;
48      while (true)
49      {
50          PRINT;
51          g_CondVar.wait(UL, [] {return !g_Queue.empty(); });
52          PRINT;
53          ProcessingStr = g_Queue.front();
54          cout << "Processing ----" << ProcessingStr << "----" << '\n';
55          PRINT;
56          g_Queue.pop();
57          PRINT;
58          if (ProcessingStr == "Exit")
59              break;
60          this_thread::sleep_for(50ms);
61      }
62  }
63
64  int main()
65  {
66      thread TReadInput(AddTaskToQueue);
67      thread TProcessQueue(ProcessQueue);
68  
69      TReadInput.join();
70      TProcessQueue.join();
71  }

输出如下。

AddTaskToQueue --- LINE : 28
ProcessQueue --- LINE : 43
TestString
AddTaskToQueue --- LINE : 30
AddTaskToQueue --- LINE : 32
AddTaskToQueue --- LINE : 34
AddTaskToQueue --- LINE : 28

我有几个问题我不想自己总结/我无法理解。

  1. 从输出中注意到Line: 44上从未获得锁,为什么会这样?
  2. 在Line: 33notify_one()/notify_all()中锁定互斥锁时调用是否是一种好习惯。
  3. 线程 之前是否有TProcessQueue可能开始执行TReadInput?我的意思是问n线程的执行顺序是否与它们的实例化方式相同?
  4. mutex在调用 ? 之前应该wait锁定condition_variable?。我的意思是问下面的代码是否可以?
//somecode
unique_lock<mutex> UL(Mutex, defer_lock);  //Mutex is not locked here
ConditionVariable.wait(UL, /*somecondition*/);
//someothercode
  1. 如果我将Line: 44更改为The output is below 并且在Line: 38unique_lock<mutex> UL(g_Mutex, defer_lock);上抛出异常
AddTaskToQueue --- LINE : 28
ProcessQueue --- LINE : 43
ProcessQueue --- LINE : 45
ProcessQueue --- LINE : 47
ProcessQueue --- LINE : 50
TestString
AddTaskToQueue --- LINE : 30
AddTaskToQueue --- LINE : 32
AddTaskToQueue --- LINE : 34
ProcessQueue --- LINE : 52
Processing ----TestString----
ProcessQueue --- LINE : 55
ProcessQueue --- LINE : 57
d:\agent\_work\1\s\src\vctools\crt\crtw32\stdcpp\thr\mutex.c(175): unlock of unowned mutex
ProcessQueue --- LINE : 50

为什么会发生这种情况,是什么unlock of unowned mutex

  1. 如果您发现我应该在此代码的任何其他部分使用任何更好的编程实践,请指出。

标签: c++multithreading

解决方案


  1. 您目前最大的问题很可能是您的线程sleep同时持有互斥锁。这意味着唯一一次不同线程可以拥有互斥锁的唯一时间是在 50 毫秒后的微小时间窗口内,此时互斥锁很快被释放并重新获取。您应该解决此问题,并且可能会看到不同的结果。
  2. 最好notify在锁外调用。这样做的原因是,被唤醒的线程可能会立即从那里开始运行,但随后会在互斥体上被阻塞,需要再次休眠并稍后再次被操作系统唤醒。在您的情况下,这肯定会发生,因为 Mutex 会再保持 50 毫秒。但这更多是一种效率优化,而不是正确性优化。
  3. 无法保证线程的启动顺序。
  4. 和 5/6:您只能在拥有关联互斥锁时等待条件变量,因为等待会在此期间释放互斥锁。那就是你得到的错误。

推荐阅读