Data Races
A data race is a situation, in which at least two threads access a shared variable at the same time. At least one thread tries to modify the variable.
If your program has a data race, it has undefined behaviour. This means all outcomes are possible and therefore, reasoning about the program makes no sense anymore.
Let me show you a program with a data race.
1
// addMoney.cpp
2
3
#include
<functional>
4
#include
<iostream>
5
#include
<thread>
6
#include
<vector>
7
8
struct
Account
{
9
int
balance
{
100
};
10
};
11
12
void
addMoney
(
Account
&
to
,
int
amount
){
13
to
.
balance
+=
amount
;
14
}
15
16
int
main
(){
17
18
std
::
cout
<<
std
::
endl
;
19
20
Account
account
;
21
22
std
::
vector
<
std
::
thread
>
vecThreads
(
100
);
23
24
25
for
(
auto
&
thr
:
vecThreads
)
thr
=
std
::
thread
(
addMoney
,
std
::
ref
(
account...