-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex6.cpp
38 lines (31 loc) · 1.12 KB
/
mutex6.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std;
mutex coutMutex;
void lock() {
cout << "Still waiting ..." << endl;
lock_guard<mutex> lg(coutMutex);
cout << this_thread::get_id() << endl;
}
int main() {
thread a = thread([&] { lock(); });
//deadblock situation
// {
// lock_guard<mutex> lg(coutMutex);
// cout << this_thread::get_id() << endl;
//the above mutex is shared by the main thread and until this scope exits the
//the mutex will not unlock, but the scope will exit only when thread completes execution, but the thread cannot complete execution since cout is guarded
// a.join();
// }
//Solution is to change position of join
{
a.join();
lock_guard<mutex> lg(coutMutex);
cout << this_thread::get_id() << endl;
//the above mutex is shared by the main thread and until this scope exits the
//the mutex will not unlock, but the scope will exit only when thread completes execution, but the thread cannot complete execution since cout is guarded
}
return 0;
}