[英]Efficiently wait for a flag state change without blocking resources?
线程无限循环地等待直到标志状态改变,然后调用函数。
伪代码插图:
while (true)
{
while (!flag)
{
sleep(1);
}
clean_upfunction();
}
目前 :
没有:
题:
对于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。
它是便携式的,比特定于平台的选件更易于使用。 而且,IIUC是即将建模的即将发布的C ++ 0x std :: condition_variable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.