mczarnek
mczarnek

Reputation: 1383

C++ Thread Safety: If only one thread can write to a non-atomic variable but multiple threads read from it.. can problems be encountered?

If one thread reads a non-atomic primitive variable another thread is writing to, is it guaranteed to read the value either before or after the write or can it somehow read some corrupt version during the write?

I realize collection such as a linked list are another story.

Upvotes: 6

Views: 1311

Answers (1)

David Schwartz
David Schwartz

Reputation: 182743

No, there are no guarantees whatsoever.

Though I really should stop there because it's a complete answer, if you think "how could this possibly go wrong", consider an implementation where a write to a non-atomic variable isn't atomic. So if you have 0x2F written and then write 0x30, it's possible that another thread might read the first nibble before the write and the second nibble after and get 0x20.

Also, suppose a non-atomic variable has the value zero and this code runs:

#define LAUNCH 1
#define DO_NOT_LAUNCH 0

if (war_has_been_declared)
     non_atomic_variable = LAUNCH;
else
     non_atomic_variable = DO_NOT_LAUNCH;

No rule prohibits the implementation from optimizing the code to this:

non_atomic_variable = LAUNCH;
if (! war_has_been_declared)
     non_atomic_variable = DO_NOT_LAUNCH;

Which means another thread might see a LAUNCH order even if war has not been declared!

But it's important to remember that there simply aren't any guarantees. It doesn't matter whether or not you can think of a plausible way it can go wrong.

Upvotes: 11

Related Questions