forked from oils-for-unix/oils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_race_test.cc
85 lines (64 loc) · 1.72 KB
/
data_race_test.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
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
// cpp/data_race_test.cc
//
// The idea behind this test is that these two questions have the SAME answer:
//
// 1. Is it safe to perform ops X and Y in 2 different threads, without
// synchronization? (If they share nontrivial state, then NO.)
// 2. Is it safe to perform op X in a signal handler, and op Y in the main
// thread, without synchronization?
#include <pthread.h>
#include <map>
#include "cpp/core.h"
#include "mycpp/runtime.h"
#include "vendor/greatest.h"
// Example from
// https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual
typedef std::map<std::string, std::string> map_t;
void* MapThread(void* p) {
map_t& m = *(static_cast<map_t*>(p));
m["foo"] = "bar";
return nullptr;
}
TEST tsan_demo() {
map_t m;
pthread_t t;
#if 1
pthread_create(&t, 0, MapThread, &m);
printf("foo=%s\n", m["foo"].c_str());
pthread_join(t, 0);
#endif
PASS();
}
void* ListThread(void* p) {
List<Str*>* mylist = static_cast<List<Str*>*>(p);
mylist->append(StrFromC("thread"));
return nullptr;
}
TEST list_test() {
List<Str*>* mylist = nullptr;
StackRoots _roots({&mylist});
mylist = NewList<Str*>({});
mylist->append(StrFromC("main"));
pthread_t t;
pthread_create(&t, 0, ListThread, mylist);
// DATA RACE DETECTED by ThreadSanitizer! Remove this line, and it goes
// away.
mylist->append(StrFromC("concurrent"));
pthread_join(t, 0);
PASS();
}
TEST global_trap_state_test() {
log("global_trap_state_test");
PASS();
}
GREATEST_MAIN_DEFS();
int main(int argc, char** argv) {
gHeap.Init();
GREATEST_MAIN_BEGIN();
RUN_TEST(tsan_demo);
RUN_TEST(list_test);
RUN_TEST(global_trap_state_test);
gHeap.CleanProcessExit();
GREATEST_MAIN_END(); /* display results */
return 0;
}