我正在编写一个练习程序来理解 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
我有几个问题我不想自己总结/我无法理解。
- 从输出中注意到Line: 44上从未获得锁,为什么会这样?
- 在Line: 33
notify_one()/notify_all()中锁定互斥锁时调用是否是一种好习惯。 - 线程 之前是否有
TProcessQueue可能开始执行TReadInput?我的意思是问n线程的执行顺序是否与它们的实例化方式相同? mutex在调用 ? 之前应该wait锁定condition_variable?。我的意思是问下面的代码是否可以?
//somecode
unique_lock<mutex> UL(Mutex, defer_lock); //Mutex is not locked here
ConditionVariable.wait(UL, /*somecondition*/);
//someothercode
- 如果我将Line: 44更改为The output is below 并且在Line: 38
unique_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?
- 如果您发现我应该在此代码的任何其他部分使用任何更好的编程实践,请指出。