C信号量,没有任何输出(可能是死锁)

时间:2017-04-27 20:24:15

标签: c semaphore

我无法弄清楚问题。

应按顺序1,2,3和4执行功能:

#include <stdio.h> //standard input/output
#include <pthread.h> //para usar threads

#include <unistd.h>     // para hacer sleep
#include <stdlib.h>     // para libreria de numeros random: srand, rand
#include <time.h>       // para tomar el tiempo
#include <semaphore.h>


#define NUM_THREADS 4
sem_t movimiento1;
sem_t movimiento2;
sem_t movimiento3;

//cada funcion tocar_movimiento_i toca una parte de la melodia
void* tocar_movimiento_1 (void* parametro)
{   
       //system("mplayer -really-quiet file_1.mp3");
       printf("1");
       sem_post(&movimiento1);
       pthread_exit(NULL); 
}

void* tocar_movimiento_2 (void* parametro)
{   
       sem_wait(&movimiento1);
       //system("mplayer -really-quiet file_2.mp3");
       printf("2");
       sem_post(&movimiento2);
       pthread_exit(NULL);
}

void* tocar_movimiento_3 (void* parametro)
{   
       sem_wait(&movimiento2);
       //ystem("mplayer -really-quiet file_3.mp3");
       printf("3");
       pthread_exit(NULL);
       sem_post(&movimiento3);
}

void* tocar_movimiento_4 (void* parametro)
{      
       sem_wait(&movimiento3);
       //system("mplayer -really-quiet file_4.mp3");
       printf("4");
       pthread_exit(NULL);
}

int main ()
{
    sem_init(&movimiento1, 0, 0);
    sem_init(&movimiento2, 0, 0);
    sem_init(&movimiento3, 0, 0);
    pthread_t threads[NUM_THREADS]; //una variable de tipo pthread_t sirve para identificar cada hilo que se cree
                                       //la variable threads es una array de pthread_t
                                       //comparar con char data[100], un array de char                                           

    //genero los threads y los lanzo, observar que sin semaforos se ejecutan los 4 casi al mismo tiempo
    //y no se reconoce la melodía       
    int rc;
       rc = pthread_create(&threads[1], NULL, tocar_movimiento_2, NULL );
       rc = pthread_create(&threads[0], NULL, tocar_movimiento_1, NULL );
       rc = pthread_create(&threads[3], NULL, tocar_movimiento_4, NULL );
       rc = pthread_create(&threads[2], NULL, tocar_movimiento_3, NULL );


    //esperar a que los threads terminen para terminar el programa principal
    int i;
        for(i = 0 ; i < NUM_THREADS ; i++)
        {
            pthread_join(threads[i] , NULL);
        }

    pthread_exit(NULL);
    return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:1)

void* tocar_movimiento_3 (void* parametro)
{   
       sem_wait(&movimiento2);
       //ystem("mplayer -really-quiet file_3.mp3");
       printf("3");
       pthread_exit(NULL);
       sem_post(&movimiento3);
}

pthread_exit的调用永远不会返回,因此对sem_post的调用永远不会发生。你的代码只在终止时产生输出(你永远不会刷新stdout),所以如果它没有终止,你将得不到输出。