需要互斥量来保护条件变量 [英] Mutex are needed to protect the Condition Variables
问题描述
据说需要Mutex来保护条件变量.
As it is said that Mutex are needed to protect the Condition Variables.
这里是对声明为pthread_cond_t
的实际条件变量的引用
或
普通共享变量count
,其值决定信令并等待.
?
Is the reference here to the actual condition variable declared as pthread_cond_t
OR
A normal shared variable count
whose values decide the signaling and wait.
?
推荐答案
这里引用的是声明为pthread_cond_t的实际条件变量还是正常的共享变量计数,其值决定了信令并等待?
is the reference here to the actual condition variable declared as pthread_cond_t or a normal shared variable count whose values decide the signaling and wait?
两者都引用.
互斥锁使得可以检查共享变量(问题中的count
),并且如果该变量的值不满足所需条件,则在pthread_cond_wait()
内部执行的等待将自动发生关于那张支票.
The mutex makes it so that the shared variable (count
in your question) can be checked and if the value of that variable doesn't meet the desired condition the wait that is performed inside pthread_cond_wait()
will occur atomically with respect to that check.
互斥锁要解决的问题是,您需要执行两个单独的操作,这些操作必须是原子的:
The problem being solved with the mutex is that you have two separate operations that need to be atomic:
- 检查
count
的条件
- 如果尚未满足条件,请等待
pthread_cond_wait()
的insode.
- check the condition of
count
- wait insode of
pthread_cond_wait()
if the condition isn't met yet.
pthread_cond_signal()
不会持久"-如果没有线程在pthread_cond_t
对象上等待,则信号不执行任何操作.因此,如果没有互斥体使上面列出的两个操作相互之间成为原子,那么您可能会遇到以下情况:
A pthread_cond_signal()
doesn't 'persist' - if there are no threads waiting on the pthread_cond_t
object, a signal does nothing. So if there wasn't a mutex making the two operations listed above atomic with respect to one another you could find yourself in the following situation:
- 一旦
count
不为零,线程A便想做某事 -
线程B在递增
count
时将发出信号(这会将count
设置为非零值)
- Thread A wants to do something once
count
is non-zero Thread B will signal when it increments
count
(which will setcount
to something other than zero)
- 线程"A"检查
count
并发现它为零 - 在"A"调用
pthread_cond_wait()
之前,线程"B"出现并且将count
递增到1并调用pthread_cond_signal()
.该调用实际上没有任何后果,因为"A"尚未在pthread_cond_t
对象上等待. - "A"调用
pthread_cond_wait()
,但是由于条件变量信号不被记住,因此它将在此时阻塞并等待已经出现或消失的信号.
- thread "A" checks
count
and finds that it's zero - before "A" gets to call
pthread_cond_wait()
, thread "B" comes along and incrementscount
to 1 and callspthread_cond_signal()
. That call actually does nothing of consequence since "A" isn't waiting on thepthread_cond_t
object yet. - "A" calls
pthread_cond_wait()
, but since condition variable signals aren't remembered, it will block at this point and wait for the signal that has already come and gone.
互斥锁(只要所有线程都遵循规则)就可以使项目#2不会出现在项目1和3之间.线程"B"将有机会递增count
的唯一方法是在A查看count
之前或在"A"已经在等待信号之后.
The mutex (as long as all threads are following the rules) makes it so that item #2 cannot occur between items 1 and 3. The only way that thread "B" will get a chance to increment count
is either before A looks at count
or after "A" is already waiting for the signal.
这篇关于需要互斥量来保护条件变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!