Skip to content

Commit 772dfa6

Browse files
committed
atomic added
1 parent b1a5ef8 commit 772dfa6

File tree

3 files changed

+284
-62
lines changed

3 files changed

+284
-62
lines changed

docs/atomic.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
2+
3+
The followings will print `200`, since each thread will increase the counter 100,
4+
```cpp
5+
int main() {
6+
int counter = 0;
7+
8+
auto work = [&]() {
9+
for (int i = 0; i < 100; i++)
10+
counter += 1;
11+
};
12+
13+
std::thread t1(work);
14+
std::thread t2(work);
15+
16+
t1.join();
17+
t2.join();
18+
19+
std::cout << counter << std::endl;
20+
return 0;
21+
}
22+
```
23+
24+
In the above example since the value `100` is very small, both of thread can finish the loop before have any effect on each other (without any interleave),
25+
however if we increase the length of the loop, threads might have impact each other, and update the value of counter while the other one has just read it,
26+
so we have data race problem.
27+
28+
```cpp
29+
int main() {
30+
int counter = 0;
31+
32+
auto work = [&]() {
33+
for (int i = 0; i < 1000000; i++)
34+
counter += 1;
35+
};
36+
37+
std::thread t1(work);
38+
std::thread t2(work);
39+
40+
t1.join();
41+
t2.join();
42+
43+
std::cout << counter << std::endl;
44+
return 0;
45+
}
46+
```
47+
which in different run gives us:
48+
49+
```
50+
1098330
51+
1261226
52+
1617594
53+
1188436
54+
```
55+
56+
57+
The solution is to make the `counter` of type `std::atomic<int>;`
58+
59+
60+
```cpp
61+
int main() {
62+
std::atomic<int> counter = 0;
63+
64+
auto work = [&]() {
65+
for (int i = 0; i < 1000000; i++)
66+
counter += 1;
67+
};
68+
69+
std::thread t1(work);
70+
std::thread t2(work);
71+
72+
t1.join();
73+
t2.join();
74+
75+
std::cout << counter << std::endl;
76+
return 0;
77+
}
78+
```
79+
80+
Refs: [1](https://www.youtube.com/watch?v=ZWjVa1kfE7c)

0 commit comments

Comments
 (0)