-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc28_mutex.cpp
More file actions
42 lines (37 loc) · 891 Bytes
/
c28_mutex.cpp
File metadata and controls
42 lines (37 loc) · 891 Bytes
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
38
39
40
41
42
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std::literals;
std::mutex m;
void foo1()
{
std::cout << "foo1 locking mutex" << std::endl;
m.lock();
std::cout << "foo1 locked mutex" << std::endl;
std::this_thread::sleep_for(500ms);
std::cout << "foo1 unlocking mutex" << std::endl;
m.unlock();
}
void foo2()
{
std::this_thread::sleep_for(100ms);
std::cout << "foo2 locking mutex" << std::endl;
while (!m.try_lock())
{
std::cout << "foo2 cannot acquire mutex" << std::endl;
std::this_thread::sleep_for(100ms);
}
std::cout << "foo2 locked mutex" << std::endl;
std::this_thread::sleep_for(100ms);
std::cout << "foo2 unlocking mutex" << std::endl;
m.unlock();
}
int main()
{
std::thread t1{foo1};
std::thread t2{foo2};
t1.join();
t2.join();
return 0;
}