2011-10-26 3 views
2

私は3つのスレッドからの信号を待っている2つのスレッドを持つつもりです。どこでデッドロックが発生しますか?

これらの2つのスレッドは同じ作業を行いますが、そのうちの1つだけが信号を取得します。一定の条件が満たされると(捕捉された信号の数)、それらは終了する。

最後に、メインスレッドは3番目のスレッドをキャンセルします。

私はデッドロック状態になりましたが、どこに問題があるのか​​わかりませんでした。

func1または func2終了あなたがミューテックスをアンロックしていない
#include <pthread.h> 
#include <stdio.h> 

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; 

int n = 0; 
int count = 0; 

void* func1(void *ptr) 
{ 
    while(1) 
    { 
     pthread_mutex_lock(&mutex); 

     // wait for func3 to signal 
     pthread_cond_wait(&cond, &mutex); 
     count++; 

     if(count > 10) 
     { 
      printf("number %d terminate func1\n", n); 
      return (NULL); 
     } 
     else 
     { 
      printf("func1 got number:%d\n", n); 
     } 
     pthread_mutex_unlock(&mutex); 
    } 
} 

void* func2(void *ptr) 
{ 
    while(1) 
    { 
     pthread_mutex_lock(&mutex); 

     // wait for func3 to signal 
     pthread_cond_wait(&cond, &mutex); 
     count++; 

     if(count > 10) 
     { 
      printf("number %d terminate func2\n", n); 
      return (NULL); 
     } 
     else 
     { 
      printf("func2 got number:%d\n", n); 
     } 
     pthread_mutex_unlock(&mutex); 
    } 
}  

void* func3(void *ptr) 
{ 
    while(1) 
    { 
     pthread_mutex_lock(&mutex); 
     n++; 
     pthread_cond_signal(&cond); 
     pthread_mutex_unlock(&mutex); 
    } 
} 


int main(int argc, char *argv[]) 
{ 
    pthread_t t1, t2, t3; 

    pthread_create(&t1, NULL, func1, NULL); 
    pthread_create(&t2, NULL, func2, NULL); 
    pthread_create(&t3, NULL, func3, NULL); 

    pthread_join(t1, NULL); 
    pthread_join(t2, NULL); 

    pthread_cancel(t3); 

    return 0; 
} 
+1

'return(NULL);' < - それ以外の副作用にはどのような影響がありますか?プログラムの流れはどのように変化しますか? –

答えて

5

+0

thx非常に、私は戻り値(NULL)をロック/アンロックスコープの外に移動しました。現在は動作します。 – zhanwu

4

私は問題が(pst points outのように)あなたのfunc1func2の機能にはreturn (NULL);だと思います。ミューテックスとpthread_cond_wait(3posix)リターンがロックされているので、彼らが終了すると、mutexがロックされて残っている:

These functions atomically release mutex and cause the 
    calling thread to block on the condition variable cond; 
    ... 
    Upon successful return, the mutex shall have been locked and 
    shall be owned by the calling thread. 

return (NULL);前にmutexをロック解除してください。

+0

はい、確かにthx – zhanwu

関連する問題