Is it safe to delete a C ++ variable here?

Is it safe to remove volatile from the m_flag definition here? If m_flag not mutable, that would stop compilers from optimizing this loop condition: while (!m_flag) m_cv.wait(lock); ? Is the standard (post-C ++ 11) specifically indicate that such optimization is prohibited in such cases?

 #include <mutex> #include <condition_variable> #include <future> #include <iostream> using namespace std; class foofoo { volatile bool m_flag; mutex m_mutex; condition_variable m_cv; public: void DoWork() { m_flag = false; unique_lock<mutex> lock(m_mutex); auto junk = async(std::launch::async, [this]() { { unique_lock<mutex> lock(m_mutex); m_flag = true; } m_cv.notify_one(); }); while (!m_flag) m_cv.wait(lock); cout << "ququ" << endl; } }; int main() { foofoo f; f.DoWork(); } 
+6
source share
2 answers

In general, volatile and multithreading are orthogonal in C ++ 11. Using volatile does not add or remove data races.

In this case, m_flag = true; is sequenced before the mutex is released in the thread started by async ([intro.execution] / p14), which, in turn, is synchronized with the subsequent acquisition of the mutex in m_cv.wait(lock) ([thread.mutex.requirements.mutex] / p11, 25), which, in turn, is sequenced before the subsequent reading of m_flag . m_flag = true; therefore, inter-thread occurs earlier and therefore occurs until the next subsequent read. ([Intro.multithread] / p13-14)

Since there are no other side effects on m_flag , m_flag = true; - a visible side effect with respect to this reading ([intro.multithread] / p15), and therefore the reading should read what was saved as a visible side effect, i.e. true

A compiler that "optimizes" this condition, regardless of whether volatile , will be a mismatch.

+10
source

You have a wait call inside the loop, so the compiler cannot fix it. Besides the fact that wait can be more or less opaque to the compiler, it contains a mutex lock / unlock inside it, which effectively prevents the compiler from throwing any exceptions. So volatile is completely useless here.

+1
source

Source: https://habr.com/ru/post/985235/


All Articles