mercredi 15 avril 2015

Is it safe to remove the c++ volatile here?

Is it safe to remove volatile from the definition of m_flag here? If m_flag is not volatile, what would stop compilers from optimizing away this loop: while (!m_flag) m_cv.wait(lock); ? Does the standard (post-C++11) specify explictly that such loops can't be optimized away 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();
}

Aucun commentaire:

Enregistrer un commentaire