我对pthread cond_signal和pthread cond_wait有疑问。例如,在下面的代码中,根据我的理解,当inc_count调用pthread_cond_signal时,只有在inc_count中的count_mutex被解锁后,才能执行count+=125 in watch_count。
当执行pthread cond_wait时,count_mutex在watch_count中被解锁,只有在执行pthread_mutex_unlock in 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);
}

最佳答案

pthread_cond_wait()解锁入口上的互斥锁,并在退出时再次锁定。如果另一个线程在此期间获取锁,pthread_cond_wait()在另一个线程释放锁之前无法返回。
因此,如果watch_count()pthread_cond_wait()中被阻塞,并且inc_count()运行并调用pthread_cond_signal(),则watch_count()pthread_cond_wait()调用inc_count()之前不会从pthread_mutex_unlock()返回。
然而,pthread_cond_wait()可以唤醒,即使没有信号。这被称为虚假的觉醒。因此watch_count()可以多次执行count+=125,即使inc_count()从不运行或从不调用pthread_cond_signal()

关于c - 关于pthread_cond_signal和pthread_cond_wait,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6505567/

10-08 20:38