-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsample_spin_lock4.cpp
More file actions
62 lines (52 loc) · 1.4 KB
/
sample_spin_lock4.cpp
File metadata and controls
62 lines (52 loc) · 1.4 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <chrono>
#include <thread>
#include <iostream> // std::cout
#include "spin_lock.hpp" // SpinLock
std::chrono::milliseconds interval(100);
SpinLock mutex;
int job_shared = 0; // both threads can modify 'job_shared',
// mutex will protect this variable
int job_exclusive = 0; // only one thread can modify 'job_exclusive'
// no protection needed
// this thread can modify both 'job_shared' and 'job_exclusive'
void job_1()
{
std::this_thread::sleep_for(interval); // let 'job_2' take a lock
while (true) {
// try to lock mutex to modify 'job_shared'
if (mutex.try_lock()) {
std::cout << "job shared (" << job_shared << ")\n";
mutex.unlock();
return;
} else {
// can't get lock to modify 'job_shared'
// but there is some other work to do
++job_exclusive;
std::cout << "job exclusive (" << job_exclusive << ")\n";
std::this_thread::sleep_for(interval);
}
}
}
// this thread can modify only 'job_shared'
void job_2()
{
mutex.lock();
std::this_thread::sleep_for(5 * interval);
++job_shared;
mutex.unlock();
}
int main()
{
std::thread thread_1(job_1);
std::thread thread_2(job_2);
thread_1.join();
thread_2.join();
}
/*
Possible output:
job exclusive (1)
job exclusive (2)
job exclusive (3)
job exclusive (4)
job shared (1)
*/