-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrace.cpp
More file actions
79 lines (65 loc) · 1.56 KB
/
race.cpp
File metadata and controls
79 lines (65 loc) · 1.56 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
/* This is free and unencumbered software released into the public domain.
* Refer to LICENSE.txt in this directory. */
/* Program demonstrating a race condition caused by unsafe concurrent memory access. */
#include <assert.h>
#include <unistd.h>
#include <iostream>
#include <mutex>
#include <random>
#include <thread>
/*
* Returns a random integer in the range [0, max]
*/
static int
random_int(int max)
{
static std::random_device rd;
static std::mt19937 generator(rd());
static std::uniform_int_distribution<int> distribution(0, max);
return distribution(generator);
}
static int g_value = 0;
static std::mutex g_mutex;
void
threadfn1()
{
for (int i = 0;; ++i)
{
/* Take ownership of g_mutex for the duration of this scoped block. */
const std::lock_guard<std::mutex> lock(g_mutex);
if (i % (10 * 1000) == 0)
{
std::cout << __FUNCTION__ << ": i=" << i << "\n";
}
/* Increment <g_value>. Should be safe because we own g_mutex. */
int old_value = g_value;
int a = random_int(5);
g_value += a;
assert(g_value == old_value + a);
(void)old_value;
}
}
void
threadfn2()
{
for (int i = 0;; ++i)
{
if (i % (100) == 0)
{
std::cout << __FUNCTION__ << ": i=" << i << "\n";
}
g_value += 1; /* Unsafe. */
usleep(10);
}
}
int
main()
{
std::thread t1(threadfn1);
std::thread t2(threadfn1);
std::thread t3(threadfn2);
t1.join();
t2.join();
t3.join();
return EXIT_SUCCESS;
}