2011-10-26 25 views
2

我打算让两个线程等待来自第三个线程的信号。导致僵局的地方?

这两个线程完成相同的工作,但其中只有一个线程同时获取信号。一旦满足某个条件(捕捉到的信号的数量),它们自行终止。

然后最后主线程取消第三个线程。

我有死锁,但无法弄清楚问题出在哪里。

#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);'< - 这有什么其他副作用(或没有,视情况而定)?它如何改变程序流程? – 2011-10-26 23:46:09

回答

5

你不是解锁互斥时func1func2退出。

+0

thx非常多,我把return(NULL)移出了锁定/解锁范围,现在它的工作原理是 – zhanwu

4

我认为问题是(如pst points outreturn (NULL);在您的func1func2函数中;因为pthread_cond_wait(3posix)返回时,互斥锁,当他们退出,互斥留锁定:

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);之前解锁你的互斥量。

+0

yes的确,thx – zhanwu