英文:
order of calling pthread_cond_signal and change condition variable
问题
我知道pthread_cond_signal/pthread_cond_broadcast应该在更改条件变量后调用,以指示条件的更改,但如果它们都在持有锁的情况下发生,顺序是否重要?例如
- pthread_mutex_lock(&mutex);
- pthread_cond_signal(&cond);
- condition = true
- 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
- pthread_mutex_lock(&mutex);
- pthread_cond_signal(&cond);
- condition = true
- 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论