C信号量,没有得到任何输出(可能是死锁)
我想不出这个问题 功能应按顺序1、2、3和4执行:C信号量,没有得到任何输出(可能是死锁),c,semaphore,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 <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;
}
对pthread_exit的调用永远不会返回,因此对sem_post的调用永远不会发生。您的代码只有在终止时才产生输出—您永远不会刷新标准输出,因此如果它不终止,您将不会得到任何输出。如果您提供一个关于您实际看到的行为以及您期望的行为的描述,这会有所帮助。还有使用的编译器和运行的操作系统是什么。@RichardChambers我希望它打印1,然后打印2,3,4参见printfWow,我错过了它。多谢各位
void* tocar_movimiento_3 (void* parametro)
{
sem_wait(&movimiento2);
//ystem("mplayer -really-quiet file_3.mp3");
printf("3");
pthread_exit(NULL);
sem_post(&movimiento3);
}