我有以下问题pthread_cond_信号 and pthread_cond_wait。例如,在下面的代码中,根据我的理解,当增量计数 calls pthread_cond_信号, 计数 += 125 in 观看次数只能在之后执行计数互斥体已解锁于增量计数.
The 计数互斥体被解锁于观看次数 when pthread_cond_wait执行并仅在之后被锁定pthread_mutex_unlock in 增量计数被执行。我对吗?
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i = 0; i < TCOUNT; i++)
{
pthread_mutex_lock(&count_mutex);
count++;
if (count == COUNT_LIMIT)
{
pthread_cond_signal(&count_threshold_cv);
}
pthread_mutex_unlock(&count_mutex);
}
pthread_exit(NULL);
}
void *watch_count(void *t)
{
long my_id = (long)t;
pthread_mutex_lock(&count_mutex);
while (count < COUNT_LIMIT)
{
pthread_cond_wait(&count_threshold_cv, &count_mutex);
count += 125;
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(NULL);
}
pthread_cond_wait()
在进入时解锁互斥体并在退出时再次锁定它。如果另一个线程在此期间获取了锁,pthread_cond_wait()
在其他线程释放锁之前无法返回。
So, if watch_count()
被封锁在pthread_cond_wait()
, and inc_count()
运行和调用pthread_cond_signal()
, then watch_count()
不会返回pthread_cond_wait()
until inc_count()
已致电pthread_mutex_unlock()
.
然而,pthread_cond_wait()
即使没有发出信号也可以唤醒。这称为虚假唤醒。watch_count()
因此可以执行count+=125
很多时候,即使inc_count()
从不运行,或从不调用pthread_cond_signal()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)