pthread condition variables on Linux, odd behaviour

前端 未结 4 891
情深已故
情深已故 2021-01-20 01:49

I\'m synchronizing reader and writer processes on Linux.

I have 0 or more process (the readers) that need to sleep until they are woken up, read a resource, go back

4条回答
  •  忘掉有多难
    2021-01-20 02:31

    The documentation says that it should work... are you sure it's the same conditional value that the rest of the threads are looking at?

    This is the example code from opengroup.org:

    pthread_cond_wait(mutex, cond):
        value = cond->value; /* 1 */
        pthread_mutex_unlock(mutex); /* 2 */
        pthread_mutex_lock(cond->mutex); /* 10 */
        if (value == cond->value) { /* 11 */
            me->next_cond = cond->waiter;
            cond->waiter = me;
            pthread_mutex_unlock(cond->mutex);
            unable_to_run(me);
        } else
            pthread_mutex_unlock(cond->mutex); /* 12 */
        pthread_mutex_lock(mutex); /* 13 */
    
    
    pthread_cond_signal(cond):
        pthread_mutex_lock(cond->mutex); /* 3 */
        cond->value++; /* 4 */
        if (cond->waiter) { /* 5 */
            sleeper = cond->waiter; /* 6 */
            cond->waiter = sleeper->next_cond; /* 7 */
            able_to_run(sleeper); /* 8 */
        }
        pthread_mutex_unlock(cond->mutex); /* 9 */
    

提交回复
热议问题