ARTICLE AD BOX
I've seen many articles saying that without locking, there might be compiler reordering, CPU instruction reordering, etc. However, I checked the compiled code and found no such reordering. I believe compilers wouldn't likely reorder notify_one before simple write operations. So, on an x86-64 CPU, will the consumer always read data as 42? I've run this many times and always got this value. I'm using GCC version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.2).
Simply put, I want to know: on an x86-64 CPU, if the producer doesn't use locking and executes data=xxx, then ready=true, then notify_one, and the consumer uses cv.wait(lock, [] { return ready; }), will the consumer always read the latest value of data? Why?
#include <iostream> #include <thread> #include <mutex> #include <condition_variable> #include <chrono> std::mutex mtx; std::condition_variable cv; bool ready = false; int data = 0; void producer() { std::this_thread::sleep_for(std::chrono::milliseconds(100)); data = 42; ready = true; cv.notify_one(); } void consumer() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [] { return ready; }); if (data != 42) { std::cout << "error: data=" << data << std::endl; } } int main() { for (int i = 0; i < 5; i++) { data = 0; ready = false; std::thread t2(consumer); std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::thread t1(producer); t1.join(); t2.join(); } return 0; }