- 论坛徽章:
- 0
|
10可用积分
我写了一个等待条件的demo,没想到产生了死锁:
- #include <pthread.h>
- #include <stdio.h>
- #include <string.h>
- #include <unistd.h>
- static pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER;
- static pthread_cond_t gCond = PTHREAD_COND_INITIALIZER;
- static int Num = 0;
- void* Run1( void* arg )
- {
- int err;
- if( 0 != ( err = pthread_mutex_lock( &gMutex ) ) )
- {
- fprintf( stderr, "Run1 lock error:%s\n", strerror( err ) );
-
- return NULL;
- }
- fprintf( stderr, "Thread1 runing!\n" );
-
- while( Num != 100 )
- {
- pthread_cond_wait( &gCond, &gMutex );
- }
- pthread_mutex_unlock( &gMutex );
- return NULL;
- }
- void StartThd1()
- {
- pthread_t thd;
- int err;
- if( 0 != ( err = pthread_create( &thd, NULL, Run1, NULL ) ) )
- {
- fprintf( stderr, "Failed to create thread1:%s\n",
- strerror( err ) );
- return;
- }
- pthread_join( thd, NULL );
- }
- void* Run2( void* arg )
- {
- int err;
- if( 0 != ( err = pthread_mutex_lock( &gMutex ) ) )
- {
- fprintf( stderr, "Run2 lock error:%s\n", strerror( err ) );
-
- return NULL;
- }
- fprintf( stderr, "Thread2 runing!\n" );
- Num = 0;
- while( Num++ != 100 );
- pthread_cond_signal( &gCond );
- pthread_mutex_unlock( &gMutex );
- return NULL;
- }
- void StartThd2()
- {
- pthread_t thd;
- int err;
- if( 0 != ( err = pthread_create( &thd, NULL, Run2, NULL ) ) )
- {
- fprintf( stderr, "Failed to create thread2:%s\n",
- strerror( err ) );
- return;
- }
- pthread_join( thd, NULL );
- }
- int main( int argc, char** argv )
- {
- StartThd1();
- StartThd2();
- return 0;
- }
复制代码
thread1一直就死了,thread2一直没有运行.
调换thread1, thread2的顺序也不行,依然死锁.
好像pthread_cond_signal( )和pthread_cond_wait()没有起到作用.
请大家解释一下原因,Thx!!!!!! |
最佳答案
查看完整内容
楼主,你要什么效果呢,你的调试信息太少了。你试试下面这个程序#include #include #include #include static pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t gCond = PTHREAD_COND_INITIALIZER;static int Num = 0;void* Run1( void* arg ){ int err; if( 0 != ( err = pthread_mutex_lock( &gMutex ) ) ) { fprintf( stderr, "Run1 lock error:%s\n", strerror ...
|