jeudi 29 janvier 2015

How to correctly serialise thread access to a flag controlling a loop

I have a function, f1, that contains a simple loop, which is controlled via a boolean flag. The flag is not written to inside f1.


I have another function that clears the flag.


The two functions are called on different threads.


If I lock the mutex before entering the loop in f1, then f2 will not be able to acquire it in order to clear the flag.


If I don't lock the mutex before entering the loop in f1, then the flag is unprotected. Does that matter, given that the function only reads it?


My question is do I need to protect the flag before entering the loop in f1, given that it is only read? If so, how?


Do I even need the mutex if the flag is only written to in one place?


Am I missing something fundamental?


TIA



class X
{
public:
X() :
m_thread(),
m_isDone(false),
m_mutex()
{
m_thread = std::unique_ptr<std::thread>(new std::thread( [=]{ run(); } ));
}

~X()
{
// tell the thread to exit
m_isDone = true;

// wait for the thread to terminate
m_thread->join();
}

void f1()
{
// locking the mutex will prevent f2 from clearing the flag
std::lock_guard<std::mutex> lock(m_mutex);

while (!m_isDone)
{
// do some stuff
}
}

void f2()
{
// lock the mutex
std::lock_guard<std::mutex> lock(m_mutex);
m_isDone = true;
}

private:
std::unique_ptr<std::thread> m_thread;
bool m_isDone;
mutable std::mutex m_mutex;
};

Aucun commentaire:

Enregistrer un commentaire