Где причины тупика? - PullRequest
       36

Где причины тупика?

2 голосов
/ 27 октября 2011

Я хочу, чтобы два потока ожидали сигналов от третьего потока.

Эти два потока выполняют одну и ту же работу, но только один из них получает сигнал одновременно. Как только определенное условие выполнено (количество захваченных сигналов), они прекращаются.

Затем в конце основной поток отменяет третий поток.

Я зашел в тупик, но не смог понять, в чем проблема.

#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 ]

5 голосов
/ 27 октября 2011

Вы не разблокируете мьютекс, когда выходит func1 или func2.

4 голосов
/ 27 октября 2011

Я думаю, что проблема (как указывает pst ) - это 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);.

...