Pot*_*ter 4 c posix pthreads condition-variable
我在网上找不到任何pthread_cond_wait在Mac OS X上出现奇怪的证据,但似乎对我来说似乎没有最简单的测试.
功能
int pthread_cond_wait(pthread_cond_t *, pthread_mutex_t * );
Run Code Online (Sandbox Code Playgroud)
应该解锁互斥参数#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;
}
Run Code Online (Sandbox Code Playgroud)
但它只获得一次锁定.主线程甚至没有尝试获取锁只是为了保持简单.
Shadow:~ dkrauss$ cc condwait.c -o condwait
Shadow:~ dkrauss$ ./condwait
expected 0
locked
signaled
expected 1
signaled
signaled
Run Code Online (Sandbox Code Playgroud)
如果我在pthread_mutex_unlock之后添加一个pthread_cond_wait,它的行为与预期一致.(或者你只希望只有一半的锁定机制.)那么,是什么给出的?
pthread_cond_wait在唤醒时重新获取互斥锁.使用pthreads互斥锁的标准模式是:
pthread_mutex_lock(&mutex);
// init work...
while (!some_condition)
pthread_cond_wait(&cond, &mutex);
// finishing work...
pthread_mutex_unlock(&mutex);
Run Code Online (Sandbox Code Playgroud)
在SUS文档中pthread_cond_wait描述了此行为:
Upon successful return, the mutex has been locked and is owned by the calling thread.
Run Code Online (Sandbox Code Playgroud)