[flext] using ThrCond with a condition variable

Spencer Russell spencer.f.russell at gmail.com
Tue Nov 22 04:23:20 CET 2011


I'm using a ThrCond to synchronize thread termination with the
destructor of the external that's using the thread. Here's what I'd
want to do:

myextern::~myextern()
{
    shouldStop = true;
    cond.Lock();
    // Use while to handle case of spurious wakeups
    while(running)
    {
        cond.Wait();
    }
    cond.Unlock();
    // Do more stuff that wants the thread to be stopped
}

// declared static, launched with LaunchThread()
myextern::ThreadedFunction()
{
    running = true;
    try
    {
        while(! shouldStop)
        {
            doStuff(); // might throw an exception
        }
    }
    catch (myException e)
    {
        handleException();
    }
    cond.Lock();
    running = false;
    cond.Signal();
    cond.Unlock();
}

Locking the conditional is important to make sure that my main thread
doesn't sit there waiting for a signal that will never come because
the thread quit in between checking the 'running' flag and then
waiting for the conditional.

The issue is that TheCond::Wait() wraps the wait in Lock and Unlock of
the associated mutex, and the mutex is declared with default
attributes, with for pthreads is non-recursive.



More information about the flext mailing list