Shared Variables
If more than one thread is sharing a variable, you have to coordinate the access. That’s the job for mutexes and locks in C++.
Data race
- A data race
- A data race is a state in which at least two threads access a shared data at the same time, and at least one of the threads is a writer. Therefore the program has undefined behaviour.
You can observe very well the interleaving of threads if a few threads write to std::cout
. The output stream std::cout
is, in this case, the shared variable.
std::cout
// withoutMutex.cpp
...
#include
<thread>
...
using
namespace
std
;
struct
Worker
{
Worker
(
string
n
)
:
name
(
n
){};
void
operator
()
(){
for
(
int
i
=
1
;
i
<=
3
;
++
i
){
this_thread
::
sleep_for
(
chrono
::
milliseconds
(
200
));
cout
<<
name
<<
": "
<<
"Work "
<<
i
<<
endl
;
}
}
private
:
string
name
;
};
thread
herb
=
thread
(
Worker
(
"Herb"
));
thread
andrei...