<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>

[{'answer_id': 34164, 'author': 'Thomi', 'author_id': 1304, 'author_profile': 'https://Stackoverflow.com/users/1304', 'pm_score': 4, 'selected': False, 'text': '<p>You never mentioned the type of finished_flag...</p>\n\n<p>If it\'s a straight <strong>bool</strong>, then it might work, but it\'s certainly bad practice, for several reasons. First, some compilers will cache the reads of the <em>finished_flag</em> 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 <strong>bool</strong> <strong>volatile</strong>, 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.</p>\n\n<p>If, on the other hand it\'s a thread-safe type, like a <a href="http://msdn.microsoft.com/en-us/library/efk30beh(VS.71).aspx" rel="nofollow noreferrer">CEvent in MFC</a> (or <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref" rel="nofollow noreferrer">equivilent in boost</a>) then you should be fine. This is the best approach: use thread-safe synchronization objects for inter-thread communication, even for simple flags.</p>\n'}, {'answer_id': 34174, 'author': 'roo', 'author_id': 716, 'author_profile': 'https://Stackoverflow.com/users/716', 'pm_score': 3, 'selected': False, 'text': '<p>Instead of using a member variable to signal that the thread is done, why not use a <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref" rel="nofollow noreferrer"><code>condition</code></a>? You are already are using the boost libraries, and <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref" rel="nofollow noreferrer"><code>condition</code></a> is part of the thread library.</p>\n\n<p>Check it <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref" rel="nofollow noreferrer">out</a>. It allows the worker thread to \'signal\' that is has finished, and the main thread can check during execution if the condition has been signaled and then do whatever it needs to do with the completed work. There are examples in the link.</p>\n\n<p>As a general case I would neve make the assumption that a resource will only be modified by the thread. You might know what it is for, however someone else might not - causing no ends of grief as the main thread thinks that the work is done and tries to access data that is not correct! It might even delete it while the worker thread is still using it, and causing the app to crash. Using a <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref" rel="nofollow noreferrer"><code>condition</code></a> will help this.</p>\n\n<p>Looking at the <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/thread/thread_management.html#thread.thread_management.thread" rel="nofollow noreferrer"><code>thread</code></a> documentation, you could also call <code>thread.timed_join</code> in the main thread. <code>timed_join</code> will wait for a specified amount for the thread to \'join\' (join means that the thread has finsihed)</p>\n'}, {'answer_id': 35460, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 3, 'selected': False, 'text': '<p>If you really want to get into the details of communication between threads via shared memory, even declaring a variable volatile won\'t be enough, even if the compiler does use appropriate access semantics to ensure that it won\'t get a stale version of data after checking the flag. The CPU can issue reads and writes out of order as long (x86 usually doesn\'t, but PPC definitely does) and there is nothing in C++9x that allows the compiler to generate code to order memory accesses appropriately.</p>\n\n<p><a href="http://www.gotw.ca/publications/index.htm" rel="nofollow noreferrer">Herb Sutter\'s Effective Concurrency</a> series has an extremely in depth look at how the C++ world intersects the multicore/multiprocessor world.</p>\n'}, {'answer_id': 69570, 'author': 'bk1e', 'author_id': 8090, 'author_profile': 'https://Stackoverflow.com/users/8090', 'pm_score': 2, 'selected': False, 'text': '<p>Having the thread set a flag (or signal an event) before it exits is a race condition. The thread has not necessarily returned to the OS yet, and may still be executing. </p>\n\n<p>For example, consider a program that loads a dynamic library (pseudocode):</p>\n\n<pre><code>lib = loadLibrary("someLibrary");\nfun = getFunction("someFunction");\nfun();\nunloadLibrary(lib);\n</code></pre>\n\n<p>And let\'s suppose that this library uses your thread:</p>\n\n<pre><code>void someFunction() {\n    volatile bool finished_flag = false;\n    thrd = new boost::thread(boost::bind(&amp;myclass::mymethod, this, &amp;finished_flag);\n    while(!finished_flag) { // ignore the polling loop, it\'s besides the point\n        sleep();\n    }\n    delete thrd;\n}\n\nvoid myclass::mymethod() {\n    // do stuff\n    finished_flag = true;\n}\n</code></pre>\n\n<p>When <code>myclass::mymethod()</code> sets <code>finished_flag</code> to <code>true</code>, <code>myclass::mymethod()</code> hasn\'t returned yet. At the very least, it still has to execute a "return" instruction of some sort (if not much more: destructors, exception handler management, etc.). If the thread executing <code>myclass::mymethod()</code> gets pre-empted before that point, <code>someFunction()</code> will return to the calling program, and the calling program will unload the library. When the thread executing <code>myclass::mymethod()</code> gets scheduled to run again, the address containing the "return" instruction is no longer valid, and the program crashes.</p>\n\n<p>The solution would be for <code>someFunction()</code> to call <code>thrd-&gt;join()</code> before returning. This would ensure that the thread has returned to the OS and is no longer executing.</p>\n'}, {'answer_id': 111694, 'author': 'oz10', 'author_id': 14069, 'author_profile': 'https://Stackoverflow.com/users/14069', 'pm_score': 3, 'selected': False, 'text': "<p>I don't mean to be presumptive, but it seems like the purpose of your <strong>finished_flag</strong> variable is to pause the main thread (at some point) until the thread <strong>thrd</strong> has completed. </p>\n\n<p>The easiest way to do this is to use <strong>boost::thread::join</strong></p>\n\n<pre><code>// launch the thread...\nthrd = new boost::thread(boost::bind(&amp;myclass::mymethod, this, &amp;finished_flag);\n\n// ... do other things maybe ... \n\n// wait for the thread to complete\nthrd.join();\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/34151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']