forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03_thread_safe_stack.cpp
More file actions
85 lines (71 loc) · 1.88 KB
/
03_thread_safe_stack.cpp
File metadata and controls
85 lines (71 loc) · 1.88 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <mutex>
#include <stack>
#include <thread>
/**
* If we take std::stack and wrap it adding mutexes to each method, we can
* achieve basic thread safety. However, it limits the true parallel access to
* the container, as only one thread could do any operation at once.
*
*/
template <typename T> class thread_safe_stack {
std::stack<T> stack;
std::mutex mutex;
public:
void push(T element) {
std::lock_guard<std::mutex> lock(mutex);
stack.push(element);
}
void pop() {
std::lock_guard<std::mutex> lock(mutex);
stack.pop();
}
T &top() {
std::lock_guard<std::mutex> lock(mutex);
return stack.top();
}
bool empty() {
std::lock_guard<std::mutex> lock(mutex);
return stack.empty();
}
size_t size() {
std::lock_guard<std::mutex> lock(mutex);
return stack.size();
}
};
int getRandZeroOrOne() { return rand() > (RAND_MAX / 2); }
/**
* Race condition inherited from the stack interface:
*
* Setup: Stack with 1 element.
* Thread 1: Accesses the if statement.
* Thread 2: Evaluates whole function.
* Thread 1: Race condition when doing top().
*/
void race_condition_example() {
thread_safe_stack<int> stack;
stack.push(0);
auto check_and_pop = [&stack]() {
if (not stack.empty()) {
// simulate race condition
std::this_thread::sleep_for(std::chrono::seconds(getRandZeroOrOne()));
int value = stack.top();
printf("The top value is: %d\n", value);
stack.pop();
}
};
std::thread t1(check_and_pop);
std::thread t2(check_and_pop);
t1.join();
t2.join();
}
int main() {
printf("Rand 0 or 1 test: %d\n", getRandZeroOrOne());
printf("Rand 0 or 1 test: %d\n", getRandZeroOrOne());
printf("Rand 0 or 1 test: %d\n", getRandZeroOrOne());
printf("Rand 0 or 1 test: %d\n", getRandZeroOrOne());
race_condition_example();
return 0;
}