Atomic Instructions and Variable Update visibility
        Posted  
        
            by dsimcha
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by dsimcha
        
        
        
        Published on 2009-10-23T16:53:22Z
        Indexed on 
            2010/06/07
            16:02 UTC
        
        
        Read the original article
        Hit count: 441
        
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:
- Is Thread 1's assignment to 
someVariableguaranteed to complete beforeatomicSet()is called? - Is Thread 2 guaranteed to see the assignment to 
someVariablebefore callingdoMoreStuff()provided it readsstuffDoneFlagatomically? 
Edits:
- The implementation of atomic ops I'm using contains the x86 
LOCKinstruction in each operation, if that helps. - Assume 
stuffDoneFlagis properly cleared somehow. How isn't important. - 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.
 
© Stack Overflow or respective owner