Skip to content

WxCondition

wxCondition variables correspond to pthread conditions or to Win32 event objects.

Example

This example shows how a main thread may launch a worker thread which starts running and then waits until the main thread signals it to continue:

class MySignallingThread : public wxThread
{
public:
    MySignallingThread(wxMutex *mutex, wxCondition *condition)
    {
        m_mutex = mutex;
        m_condition = condition;
    }
    virtual ExitCode Entry()
    {
        ... do our job ...
        // tell the other(s) thread(s) that we're about to terminate: we must
        // lock the mutex first or we might signal the condition before the
        // waiting threads start waiting on it!
        wxMutexLocker lock(*m_mutex);
        m_condition->Broadcast(); // same as Signal() here -- one waiter only
        return 0;
    }
private:
    wxCondition *m_condition;
    wxMutex *m_mutex;
};
int main()
{
    wxMutex mutex;
    wxCondition condition(mutex);
    // the mutex should be initially locked
    mutex.Lock();
    // create and run the thread but notice that it won't be able to
    // exit (and signal its exit) before we unlock the mutex below
    MySignallingThread *thread = new MySignallingThread(&mutex, &condition);
    thread->Run();
    // wait for the thread termination: Wait() atomically unlocks the mutex
    // which allows the thread to continue and starts waiting
    condition.Wait();
    // now we can exit
    return 0;
}

Favorite site