What happens and how - earlier in C ++ 0x

Can you explain the "happens first" order on an atom that is split between two threads? Consider a "read" stream and a "write" stream, both of which share an atomic boolean variable x. A thread read just reads the value of x, and a write thread just writes a value to x. Given that the scheduler can run these threads in any order, how does C ++ ensure consistent consistency between the two threads?

+3


source to share


1 answer


The rule of thumb is that if one thread writes to an atomic variable and another thread reads that variable and sees the value that was written, you have a "before" relationship. This, in turn, implies that the values ​​written in the first thread before being written to the atomic variable are visible in the second thread after it reads the atomic variable and sees the value that was written.

To use an atomic variable for synchronization, you have to do something like this:



int i = 0;
atomic<bool> ready;

// thread 1:
i = 3;
ready = true;

// thread 2:
while (!ready)
    ;  /* busy wait */
std::cout << i << '\n'; // writes "3" to cout

      

0


source







All Articles