Ben Y
Ben Y

Reputation: 311

Threads read/writing at the same time

If I don't care whether Thread1 changes Flag1 at the same time Thread2 changes Flag1, is there anything else to worry about besides logic errors? Will it cause a crash etc if:

  1. Thread1 and Thread2 read Flag1 at the exact same time?
  2. Thread1 is writing to Flag1 at the same time as Thread2 is reading Flag1?

In these examples, Flag1 is a bool.

Upvotes: 3

Views: 4016

Answers (3)

Jonathan Wakely
Jonathan Wakely

Reputation: 171491

According to the rules of the C++11 memory model:

  1. Thread1 and Thread2 read Flag1 at the exact same time? This is always safe.
  2. Thread1 is writing to Flag1 at the same times as Thread2 is reading flag1? This is a data race.

A data race is undefined behaviour. Although it's unlikely to crash on any sane hardware, it's undefined behaviour, so anything could happen.

Upvotes: 9

Samy Arous
Samy Arous

Reputation: 6812

As far as I know, 2 threads cannot access the same memory in the exact same time.

Even on parallel computing, these assumptions would be handled automatically by the processor. http://en.wikipedia.org/wiki/Parallel_Random_Access_Machine

So the answer is no crash. You will have logic errors of course but since you don't care :p.

Upvotes: 2

Chip
Chip

Reputation: 3316

The flag should be marked as volatile. This will ensure your compiler does not optimize read/writes in a way that is inconsistant.

I believe read/writes to bool are atomic - so I don't think you will have any other issues if you don't care about the order of access.

Upvotes: -1

Related Questions