<p>Is the following safe?</p>

<p>I am new to threading and I want to delegate a time consuming process to a separate thread in my C++ program.
Using the boost libraries I have written code something like this:</p>

<p>thrd = new boost::thread(boost::bind(&amp;myclass::mymethod, this, &amp;finished_flag);</p>

<p>Where finished_flag is a boolean member of my class. When the thread is finished it sets the value and the main loop of my program checks for a change in that value.
I assume that this is okay because I only ever start one thread, and that thread is the only thing that changes the value (except for when it is initialised  before I start the thread)
So is this okay, or am I missing something, and need to use locks and mutexes, etc</p>

You never mentioned the type of finished_flag...
If it's a straight
bool
, then it might work, but it's certainly bad practice, for several reasons. First, some compilers will cache the reads of the
finished_flag
variable, since the compiler doesn't always pick up the fact that it's being written to by another thread. You can get around this by declaring the
bool
volatile
, but that's taking us in the wrong direction. Even if reads and writes are happening as you'd expect, there's nothing to stop the OS scheduler from interleaving the two threads half way through a read / write. That might not be such a problem here where you have one read and one write op in separate threads, but it's a good idea to start as you mean to carry on.
If, on the other hand it's a thread-safe type, like a
CEvent in MFC
(or
equivilent in boost
) then you should be fine. This is the best approach: use thread-safe synchronization objects for inter-thread communication, even for simple flags.