Boost logo

Boost Users :

Subject: Re: [Boost-users] Race condition with Boost::Thread
From: Boost lzw (boostlzw_at_[hidden])
Date: 2009-08-27 18:17:07


Hi guys,

This threaded code can be improved further:
===============
 ~WorkerThread() {
            while (!m_Running)
                 ;
            m_Thread.join();
            m_Running = false;
      }
 ================

Endlessly polling the m_Running with an empty while loop is inefficient. It
would be better to use the boost::condition and boost::mutex for thread
synchronization [the 2nd thread notifies the 1st (main() ) one when it
completes its task]. A possible improvement can be achieved like this:
--------------Begin-------------
boost::condition taskCompleted;
boost::mutex taskMutex;

class WorkerThread { // class definition
...
~WorkerThread() {
        boost::mutex::scoped_lock lock(taskMutex);
        {
            taskCompleted.wait(lock); // wait for notification
            m_Thread.join();
         }
...
       void run() {
         boost::mutex::scoped_lock lock(taskMutex);
         {
             // work to do
             // after work is done
             taskCompleted.notify_one();// I am done, your turn now.
         } // lock scope
     } run() scope
}; // class definition
--------------end-------------
The volatile bool m_Running variable, its initialization and assignments,
and const bool isRunning() const function in the original code are no longer
needed.

Cheers,
Robert

On Thu, Jul 30, 2009 at 7:33 AM, Ilya Sokolov <ilyasokol_at_[hidden]> wrote:

> Rob Yull wrote:
>
>> WorkerThread()
>> {
>> m_Thread = boost::thread(boost::bind(&WorkerThread::run,
>> boost::ref(this)));
>>
>
> It should not compile, you need
>
> m_Thread = boost::thread(boost::bind(&WorkerThread::run, this));
>
> or simply
>
> m_Thread = boost::thread(&WorkerThread::run, this);
>
> m_Running = true;
>> }
>>
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net