views:

212

answers:

3

Thread to wait infinitely in a loop until a flag state change, then call function.

pseudo code illustration:

while (true)
{
    while (!flag)
    {
         sleep(1);
    }
    clean_upfunction();
}

Currently:

No:

  • MFC

Question:

  • Is there a more efficient way of implementing the above
  • A waitForStateChange() - similar to above - in the threading library
+10  A: 

For Windows (which you have this tagged for), you want to look at WaitForSingleObject. Use a Windows Event (with CreateEvent), then wait on it; the other thread should call SetEvent. All native Windows, no MFC or anything else required.

Nick
@Nick: Thanks - just what am looking for :)
Aaron
+2  A: 

If you're not on Windows, and are instead on a POSIXish box, pthread_cond_wait is the best match:

/* signaler */
    pthread_mutex_lock(mutex);
    flag = true;
    pthread_cond_signal(cond);
    pthread_mutex_unlock(mutex);

/* waiter */
    pthread_mutex_lock(mutex);
    do {
        pthread_cond_wait(cond, mutex);
    } while (!flag);
    pthread_mutex_unlock(mutex);

The classic self-pipe trick is easier and cooler though :) Works on systems without pthreads too.

/* setup */
    int pipefd[2];
    if (pipe(pipefd) < 0) {
        perror("pipe failed");
        exit(-1);
    }

/* signaler */
    char byte = 0;
    write(pipefd[0], &byte, 1);  // omitting error handling for brevity

/* waiter */
    char byte;
    read(pipefd[1], &byte, 1);  // omitting error handling for brevity

The waiter will block on the read (you don't set O_NONBLOCK) until interrupted (which is why you should have error handling) or the signaler writes a byte.

ephemient
Anyway of adding a timeout?
Martin Beckett
There's pthread_cond_timedwait. For the self-pipe method... you can use alarm() if you're forking, but that doesn't work too well with a threaded program.
ephemient
+2  A: 

Take a look at condition_variable in Boost.Thread.

http://www.boost.org/doc/libs/1_37_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref

It is portable, easier to use than the platform-specific options. Moreover, IIUC, the upcoming C++0x std::condition_variable was modeled after it.

Éric Malenfant