4

我在网上找不到任何pthread_cond_wait在 Mac OS X 上奇怪的证据,但它似乎没有通过对我来说最简单的测试。

功能

int pthread_cond_wait(pthread_cond_t *, pthread_mutex_t * );

应该解锁互斥量参数#2,然后等待在条件参数#1上发送信号。我编写了一个简单的程序来测试它,并测试虚假唤醒:

#include <stdio.h>
#include <pthread.h>

pthread_t spin_thread;
pthread_mutex_t spin_mutex;
pthread_cond_t spin_cond;

int actual = 0;

void *condspin( void *v ) {
    int expected = 0;
    for ( ;; ) {
        if ( actual != expected ) printf( "unexpected %d\n", actual );
        else printf( "expected %d\n", actual );
        pthread_mutex_lock( &spin_mutex );
        printf( "locked\n" );
        expected = actual + 1;
        pthread_cond_wait( &spin_cond, &spin_mutex );
    }
    return NULL;
}

int main( int argc, char ** argv ) {
    pthread_mutex_init( &spin_mutex, NULL );
    pthread_cond_init( &spin_cond, NULL );
    pthread_create( &spin_thread, NULL, &condspin, NULL );

    for ( ;; ) {
        getchar();
        pthread_cond_signal( &spin_cond );
        printf( "signaled\n" );
        ++ actual;
    }
    return 0;
}

但它只获得一次锁。为了简单起见,主线程甚至不会尝试获取锁。

Shadow:~ dkrauss$ cc condwait.c -o condwait
Shadow:~ dkrauss$ ./condwait 
expected 0
locked

signaled
expected 1

signaled

signaled

如果我在pthread_mutex_unlock之后添加 a pthread_cond_wait,它的行为将符合预期。(或者正如你所期望的那样,只有一半的锁定机制。)那么,什么给了?

4

1 回答 1

8

pthread_cond_wait唤醒时重新获取互斥锁。使用 pthreads 互斥锁的标准模式是:

pthread_mutex_lock(&mutex);
// init work...
while (!some_condition)
    pthread_cond_wait(&cond, &mutex);
// finishing work...
pthread_mutex_unlock(&mutex);

此行为在SUS 文档中pthread_cond_wait描述为:

Upon successful return, the mutex has been locked and is owned by the calling thread. 
于 2009-08-23T23:28:02.647 回答