Search code examples
cmultithreadingatomicstdatomic

Is a global variable accessed by three threads (2 writers, 1 reader) without any synchronization potentially undefined?


In a windows/linux multithreaded C program, if an unsigned int global variable is accessed by three threads without any synchronization, where

  • Thread 1 writes the value 0
  • Thread 2 writes the value 0xFFFFFFFF
  • Thread 3 reads the value

Question

Is it possible for Thread 3 to retrieve a partial value, say 0x0000FFFF from the global variable?

I've always assumed that if an unsigned int is properly aligned, a write operation is atomic, so in this case, Thread 3 would always be either 0 or 0xFFFFFFFF.


Solution

  • You forgot one very likely case: That thread 3 doesn't read the value at all, using a previously read value instead.

    Synchronization doesn't just prevent partial read/writes; it also informs the CPU and compiler that the value could be changed by another thread. They can and do assume that won't happen if there's no synchronization, so a cached value could be used, or the read can be optimized away, etc.

    (I'm using the term "synchronization" loosely here.)

    Given this possibility, it's moot whether you can end up with 0000FFFF or not.