调用pthread_cond_signal和更改条件变量的顺序

huangapple go评论61阅读模式
英文:

order of calling pthread_cond_signal and change condition variable

问题

我知道pthread_cond_signal/pthread_cond_broadcast应该在更改条件变量后调用,以指示条件的更改,但如果它们都在持有锁的情况下发生,顺序是否重要?例如

  1. pthread_mutex_lock(&mutex);
  2. pthread_cond_signal(&cond);
  3. condition = true
  4. pthread_mutex_unlock(&mutex);

等待者的唤醒必须发生在步骤4之后(以检索互斥锁),因此等待者必须已经看到了更新的条件变量。

英文:

I know that pthread_cond_signal/pthread_cond_broadcast should be called after changing the condition variable to indicate a condition change, but if they both happen with lock held, does the order matter? For example

  1. pthread_mutex_lock(&mutex);
  2. pthread_cond_signal(&cond);
  3. condition = true
  4. pthread_mutex_unlock(&mutex);

the waiter's wakeup must happen after step 4(to retrieve the mutex), so the waiter must have seen the update condition variaable

答案1

得分: 3

我认为你是对的。
如果检查这个条件的代码编写正确,这不应该是一个问题。

例如:

pthread_mutex_lock(&lock);
while(!state)
{
pthread_cond_wait(&cond, &lock);
}
pthread_mutex_unlock(&lock);

英文:

I think you are right.
If the code checking this condition is written in a correct way, this should not be a problem.

e.g.

pthread_mutex_lock(&lock);
while(!state)
{
    pthread_cond_wait(&cond, &lock);
}
pthread_mutex_unlock(&lock);

huangapple
  • 本文由 发表于 2023年6月6日 15:36:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定