【发布时间】:2011-06-28 11:17:28
【问题描述】:
我对 pthread_cond_signal 和 pthread_cond_wait 有疑问。比如下面的代码,据我了解,当inc_count调用pthread_cond_signal时,count += 125 in watch_count 只有在 inc_count 中解锁了 count_mutex 后才能执行。
count_mutex 在 pthread_cond_wait 执行时在 watch_count 中被解锁,并且仅在 中的 pthread_mutex_unlock 之后才被锁定inc_count 被执行。我说的对吗?
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);
}
【问题讨论】: