-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbadlock2.cc
46 lines (42 loc) · 916 Bytes
/
badlock2.cc
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
#include <pthread.h>
#include <vector>
pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
class C {
public:
C() {
pthread_mutex_init(&mu_, NULL);
}
void doSlowOperation() {
pthread_mutex_unlock(&g_mu);
pthread_mutex_lock(&mu_);
for (int i = 0; i < 5; i++)
vals_.push_back(i);
pthread_mutex_unlock(&mu_);
pthread_mutex_lock(&g_mu);
}
void doFastOperation() {
vals_.push_back(42);
}
private:
pthread_mutex_t mu_;
std::vector<int> vals_;
};
void* thread(void* data) {
C* c = (C*)data;
for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&g_mu);
c->doSlowOperation();
c->doFastOperation();
pthread_mutex_unlock(&g_mu);
}
return NULL;
}
int main() {
C* c = new C();
pthread_t th1;
pthread_create(&th1, NULL, &thread, c);
pthread_t th2;
pthread_create(&th2, NULL, &thread, c);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
}