forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_mutex_misusages.cpp
More file actions
55 lines (45 loc) · 1.24 KB
/
02_mutex_misusages.cpp
File metadata and controls
55 lines (45 loc) · 1.24 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
#include <cstdio>
#include <iostream>
#include <list>
#include <mutex>
#include <thread>
// =========================================================
class list_wrapper {
std::list<int> my_list;
std::mutex m;
public:
void add_to_list(int const &x) {
std::lock_guard<std::mutex> lg(m);
my_list.push_front(x);
}
void size() {
std::lock_guard<std::mutex> lg(m);
int size = my_list.size();
std::cout << "size of the list is : " << size << std::endl;
}
// PROBLEM: Function breaks mutex locking of shared resource.
std::list<int> *get_data() { return &my_list; }
};
// =========================================================
struct Data {
void foo() { printf("Hello from foo()\n"); }
};
class DataWrapper {
Data data;
std::mutex m;
public:
// Allows running any function on the data that should be protected.
// In particular, the caller can retain a reference to the data.
template <typename Fn> void bar(Fn f) {
// Guard cannot guarantee safe usage of data.
std::lock_guard<std::mutex> lg(m);
f(data);
}
};
Data *unprotected_data;
void malicious_function(Data &data) { unprotected_data = &data; }
int main() {
DataWrapper wrapper;
wrapper.bar(malicious_function);
unprotected_data->foo();
}