Race conditions are not related to whether the variable is on the heap or on the stack. A race condition is when one thread changes a variable (memory cell), and another thread reads or modifies the same variable. There is no guarantee that the modification of a bool is atomic, so the published code has a race state and therefore undefined behavior.
The fix will be to save the bool value when the mutex is held and returns a variable:
static bool IsShutdownInProgress() { pthread_mutex_lock(&mutex); bool result = shutdownInProgress; pthread_mutex_unlock(&mutex); return result; }
C ++ 11 introduced std::mutex and std::lock_guard , which can be used, and using lock_guard would avoid the requirement of a temporary variable to keep the bool value to return:
static std::mutex mtx_; static bool IsShutdownInProgress() { std::lock_guard<std::mutex> lk(mtx_); return shutdownInProgress; }
C ++ 11 also introduced std::atomic<> , which would ensure that the modification was atomic and avoided explicit blocking:
static std::atomic<bool> shutdownInProgress; static bool IsShutdownInProgress() { return shutdownInProgress; }
If C ++ 11 is not available, boost::atomic was introduced in version 1.53.0, and boost also has the equivalent of boost::mutex and boost::lock_guard .
hmjd source share