哪里导致僵局?

时间:2011-10-26 23:40:15

标签: c pthreads deadlock

我打算让两个线程等待来自第三个线程的信号。

这两个线程做同样的工作,但是其中只有一个一次获得信号。一旦某个条件满足(捕获的信号数量),它们就会自行终止。

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

我遇到了僵局,但无法弄清问题在哪里。

#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;
}

2 个答案:

答案 0 :(得分:5)

func1func2退出时,您无法解锁互斥锁。

答案 1 :(得分:4)

我认为问题是(pst points out}是return (NULL);func1函数中的func2;因为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);之前解锁互斥锁。