简体   繁体   中英

Efficiently wait for a flag state change without blocking resources?

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 :

  • Using the multithreaded versions of the 的多线程版本

No:

  • MFC

Question:

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM