pthread_cond_wait不会解锁互斥锁

时间:2009-08-23 23:16:05

标签: c pthreads posix condition-variable

我无法在网上找到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之后添加pthread_cond_wait,则其行为符合预期。 (或者你只希望只有一半的锁定机制。)那么,是什么给出了什么?

1 个答案:

答案 0 :(得分: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 documentation for pthread_cond_wait中描述为:

Upon successful return, the mutex has been locked and is owned by the calling thread.