简体   繁体   English

有效地等待标志状态更改而不会阻塞资源?

[英]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 : 目前

No: 没有:

  • MFC MFC

Question: 题:

  • Is there a more efficient way of implementing the above 是否有一种更有效的方法来实现上述目的
  • A waitForStateChange() - similar to above - in the threading library 线程库中的waitForStateChange()-与上面类似-

For Windows (which you have this tagged for), you want to look at WaitForSingleObject . 对于Windows(已对此进行了标记),您需要查看WaitForSingleObject Use a Windows Event (with CreateEvent), then wait on it; 使用Windows事件(带有CreateEvent),然后等待它; the other thread should call SetEvent. 另一个线程应调用SetEvent。 All native Windows, no MFC or anything else required. 所有本机Windows,不需要MFC或其他任何东西。

If you're not on Windows, and are instead on a POSIXish box, pthread_cond_wait is the best match: 如果您不在Windows上,而是在POSIXish框上,则pthread_cond_wait是最佳匹配:

/* 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. 经典的自管道技巧虽然更容易也更酷:)也可以在没有pthreads系统上使用。

/* 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. 服务员将阻塞read (您不设置O_NONBLOCK ),直到被中断(这就是您应该进行错误处理的原因)或发信号器写入一个字节为止。

Take a look at condition_variable in Boost.Thread. 看一下Boost.Thread中的condition_variable。

http://www.boost.org/doc/libs/1_37_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref 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. 而且,IIUC是即将建模的即将发布的C ++ 0x std :: condition_variable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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