pthread的条件循环 [英] pthread condition loop

查看:329
本文介绍了pthread的条件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了使用调用pthread_cond_wait的典型模式是:

 的pthread_mutex_lock(安培;锁定);
  而(!测试)
    调用pthread_cond_wait(安培;条件,和放大器;锁);
调用pthread_mutex_unlock(安培;锁定);

为什么不能if语句来代替while循环。

 的pthread_mutex_lock(安培;锁定);
  如果(!测试)
    调用pthread_cond_wait(安培;条件,和放大器;锁);
调用pthread_mutex_unlock(安培;锁定);


解决方案

<一个href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html\">http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html


  

在使用条件变量始终存在涉及与每个条件等待这是真的如果线程应该进行相关的共享变量布尔predicate。从那么pthread_cond_timedwait()或调用pthread_cond_wait杂散唤醒()可能出现的功能。因为从那么pthread_cond_timedwait()或pthread_cond_wait()的,并不意味着这个predicate的任何有价值的东西回归,predicate应该在这样的回报率重新评估。


,而循环是重新评估predicate非常标准的方式,所要求的POSIX。

The typical pattern I've seen for using pthread_cond_wait is:

pthread_mutex_lock(&lock);
  while (!test)
    pthread_cond_wait(&condition, &lock);
pthread_mutex_unlock(&lock);

Why can't an if statement be used instead of a while loop.

pthread_mutex_lock(&lock);
  if (!test)
    pthread_cond_wait(&condition, &lock);
pthread_mutex_unlock(&lock);

解决方案

http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html

When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.

The while loop is a very standard way of re-evaluating the predicate, as required by POSIX.

这篇关于pthread的条件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆