Search code examples
multithreadingsynchronizationmultiprocessingmemory-barriers

Is a memory barrier required if a second thread waits for termination of the first one?


Suppose that thread Alpha is writing to variable A without locking. A second thread Beta is waiting for Alpha to terminate, then reads the variable A in turn.

Is it possible that the contents of A will not be fresh? Can memory writes be delayed beyond the thread lifetime? Won't the standard mechanism of waiting for thread Alpha termination implicitly work as a memory barrier?

UPDATE 1

Are there any examples of waiting which does not include a memory barrier?


Solution

  • Almost certainly (the API used to wait for thread termination would need to use memory barriers for its own purposes), but I think for a definitive answer you'll need to talk about the specific threading API being used.

    For example, posix makes such a guarantee for pthread_join(): https://stackoverflow.com/a/3208140/12711

    And Win32 documents that it's synchronization APIs to wait on an object (for example, a thread handle) impose memory barriers: http://msdn.microsoft.com/en-us/library/ms686355.aspx