From: David Yonge-M. <dav...@gm...> - 2025-08-04 14:25:02
|
Hi, everyone, I would like some help from helgrind experts to settle a disagreement with a colleague. We have the following code (very simplified): --- begin example.cpp --- #include <pthread.h> #include <iostream> #include <atomic> bool flag = false; // std::atomic<bool> flag{false}; void* callbackEvent(void* whatever) { flag = true; return whatever; } int main(void) { pthread_t callback_thread; pthread_create(&callback_thread, NULL, callbackEvent, NULL); bool copyOfFlag = flag; if (!copyOfFlag) { std::cout << "value of flag: " << copyOfFlag << std::endl; // do stuff assuming flag is false } pthread_join(callback_thread, NULL); } --- end example.cpp --- > g++ -lpthread example.cpp -o example && valgrind --tool=helgrind ./example Running helgrind naturally produces the output that there is a data race in "flag" between the two threads. If the flag is replaced by an atomic, helgrind produces a clean report. According to my understanding, this is a false negative. There is still no "happens-before" relationship between the read in thread #1 and the write in thread #2. The program can terminate with copyOfFlag being either true or false, which means the race condition still exists. According to my colleague, helgrind by design only cares that a read and a write on the same memory does not happen at the same time, and making the bool atomic fixes this. The indeterminacy of the value of copyOfFlag is a separate issue, which helgrind cannot detect as it is not within the scope of its design. I claimed that helgrind does not understand atomic variables. My colleague disbelieved this and made the counterargument that if a mutex is used to guard access to flag (instead of making it atomic), it also produces a clean report, and since helgrind undoubtedly understands mutexes, it must mean that the data race is fixed. What is the correct view here? Thank you for your time. p.s. I am aware of bug 339330, but technically it only mentions false positives and this is a case of (what I believe to be) a false negative. -- David Yonge-Mallo |