繁体   English   中英

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

[英]Efficiently wait for a flag state change without blocking resources?

线程无限循环地等待直到标志状态改变,然后调用函数。

伪代码插图:

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

目前

没有:

  • MFC

题:

  • 是否有一种更有效的方法来实现上述目的
  • 线程库中的waitForStateChange()-与上面类似-

对于Windows(已对此进行了标记),您需要查看WaitForSingleObject 使用Windows事件(带有CreateEvent),然后等待它; 另一个线程应调用SetEvent。 所有本机Windows,不需要MFC或其他任何东西。

如果您不在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);

经典的自管道技巧虽然更容易也更酷:)也可以在没有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

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

看一下Boost.Thread中的condition_variable。

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

它是便携式的,比特定于平台的选件更易于使用。 而且,IIUC是即将建模的即将发布的C ++ 0x std :: condition_variable。

暂无
暂无

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

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