Multicore & Synchronization
In the code above, thread 1 prepares data and then signals with flag, and thread 2 waits for flag and then reads data. On a CPU with a weak memory model, what is needed for thread 2 to reliably read 42?
// Thread 1 // Thread 2
data = 42; while (flag == 0) { }
flag = 1; print(data);
- AChange the type of data from int to long
- BMake the write to flag a release and the read of flag an acquire to guarantee the order
- CMake sure thread 2's loop body is empty
Show answer and explanation
Answer: B. Make the write to flag a release and the read of flag an acquire to guarantee the order
Under a weak model, thread 1's two writes may appear reordered, or thread 2's read of data may happen before its read of flag, so data might still be stale even though flag is 1. Making the write to flag a release guarantees that earlier writes become visible first, and making the read of flag an acquire keeps later reads from running ahead of it.
- A. Changing the type does not guarantee order.
- B. Correct. data's write is guaranteed to be visible before flag's.
- C. The loop body has nothing to do with ordering.