Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real dangers of 2+ threads writing/reading a variable

Tags:

c

pthreads

What are the real dangers of simultaneous read/write to a single variable?

If I use one thread to write a variable and another to read the variable in a while loop and there is no danger if the variable is read while being written and an old value is used what else is a danger here?

Can a simultaneous read/write cause a thread crash or what happens on the low level when an exact simultaneous read/write occurs?

like image 708
some_id Avatar asked May 08 '11 12:05

some_id


2 Answers

If two threads access a variable without suitable synchronization, and at least one of those accesses is a write then you have a data race and undefined behaviour.

How undefined behaviour manifests is entirely implementation dependent. On most modern architectures, you won't get a trap or exception or anything from the hardware, and it will read something, or store something. The thing is, it won't necessarily read or write what you expected.

e.g. with two threads incrementing a variable, you can miss counts, as described in my article at devx: http://www.devx.com/cplus/Article/42725

For a single writer and a single reader, the most common outcome will be that reader sees a stale value, but you might also see a partially-updated value if the update requires more than one cycle, or the variable is split across cache lines. What happens then depends on what you do with it --- if it's a pointer and you get a partially updated value then it might not be a valid pointer, and won't point to what you intended it to anyway, and then you might get any kind of corruption or error due to dereferencing an invalid pointer value. This may include formatting your hard disk or other bad consequences if the bad pointer value just happens to point to a memory mapped I/O register....

like image 146
Anthony Williams Avatar answered Sep 20 '22 07:09

Anthony Williams


In general you get unexpected results. Wikipedia defines two distinct racing conditions:

A critical race occurs when the order in which internal variables are changed determines the eventual state that the state machine will end up in.

A non-critical race occurs when the order in which internal variables are changed does not alter the eventual state. In other words, a non-critical race occurs when moving to a desired state means that more than one internal state variable must be changed at once, but no matter in what order these internal state variables change, the resultant state will be the same.

So the output will not always get messed up, it depends on the code. It's good practice to always deal with racing conditions for later code scaling and preventing possible errors. Nothing is more annoying then not being able to trust your own data.

like image 20
orlp Avatar answered Sep 22 '22 07:09

orlp