Search code examples
multithreadingthread-safetyatomicrace-conditionmemory-fences

Atomic Instructions and Variable Update visibility


On most common platforms (the most important being x86; I understand that some platforms have extremely difficult memory models that provide almost no guarantees useful for multithreading, but I don't care about rare counter-examples), is the following code safe?

Thread 1:

someVariable = doStuff();
atomicSet(stuffDoneFlag, 1);

Thread 2:

while(!atomicRead(stuffDoneFlag)) {}  // Wait for stuffDoneFlag to be set.
doMoreStuff(someVariable);

Assuming standard, reasonable implementations of atomic ops:

  1. Is Thread 1's assignment to someVariable guaranteed to complete before atomicSet() is called?
  2. Is Thread 2 guaranteed to see the assignment to someVariable before calling doMoreStuff() provided it reads stuffDoneFlag atomically?

Edits:

  1. The implementation of atomic ops I'm using contains the x86 LOCK instruction in each operation, if that helps.
  2. Assume stuffDoneFlag is properly cleared somehow. How isn't important.
  3. This is a very simplified example. I created it this way so that you wouldn't have to understand the whole context of the problem to answer it. I know it's not efficient.

Solution

  • If your actual x86 code has the store to someVariable before the store in atomicSet in Thread 1 and load of someVariable after the load in atomicRead in Thread 2, then you should be fine. Intel's Software Developer's Manual Volume 3A specifies the memory model for x86 in Section 8.2, and the intra-thread store-store and load-load constraints should be enough here.

    However, there may not be anything preventing your compiler from reordering the instructions generated from whatever higher-level language you are using across the atomic operations.