线程执行命令但停止我的程序

时间:2017-07-27 14:04:33

标签: c pthreads

首先,我不熟悉线程,我想在不等待另一个任务的情况下完成任务,我被告知这是最好的解决方案。

所以我编写了这段代码,每当我将tab[]中的值传递给true时,它就会发出声音(我删除了部分正常工作但不引用线程的代码) :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wiringPi.h>
#include <pthread.h>

#define DRUM0 25
#define DRUM1 24
#define DRUM2 23


void *kick(void *arg)
{
        printf("Kick");
        execlp("/usr/bin/omxplayer", " ", "/home/pi/sounds/kick.wav", NULL);
        (void) arg;
        pthread_exit(NULL);
}
void *boom(void *arg)
{
        printf("Boom");
        execlp("/usr/bin/omxplayer", " ", "/home/pi/sounds/boom.wav", NULL);
        (void) arg;
        pthread_exit(NULL);
}
void *tom(void *arg)
{
        printf("tom");
        execlp("/usr/bin/omxplayer", " ", "/home/pi/sounds/tom.wav", NULL);
        (void) arg;
        pthread_exit(NULL);
}
int main()
{
        pthread_t kicking, booming, toming;
        while(1){
                if(tab[0] == 1)
                {
                        if(pthread_create(&kicking, NULL, kick, NULL) == -1) {
                                perror("pthread_create");
                                return EXIT_FAILURE;
                        }
                }

                if(tab[1] == 1)
                {
                        if(pthread_create(&booming, NULL, boom, NULL) == -1) {
                                perror("pthread_create");
                                return EXIT_FAILURE;
                        }
                }
                if(tab[2] == 1)
                {
                        if(pthread_create(&toming, NULL, tom, NULL) == -1) {
                                perror("pthread_create");
                                return EXIT_FAILURE;
                        }
                }
        }
        return 0;
}

因此,当我将tab的值传递给1时,它会激活相应的线程,但随后它会卡住并且不会执行任何操作。 在这种情况下,它播放我想要的声音,然后卡在这些行(我的程序仍在运行,但当我将另一个值传递给1或0时没有任何反应):

Audio codec pcm_s24le channels 1 samplerate 44100 bitspersample 24
Subtitle count: 0, state: off, index: 1, delay: 0

我不知道它来自哪里,也没有在任何地方找到这样的问题。我希望问题来自omxplayer或我使用execlp,但我仍然不知道如何解决我的问题,所以如果你可以提前帮助你!

[编辑]好的,所以我也尝试使用fork()

void *kick(void *arg)
{
        int pid = fork();
        if(pid == 0)
        {
                printf("Kick");
                execlp("/usr/bin/omxplayer", " ", "/home/pi/sounds/kick.wav", NULL);
                (void) arg;
        }
        else
                wait();

        pthread_exit(NULL);
}

但它给了我一个非常奇怪的omxplayer日志:

Raspberry Pi Drums
Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.have a nice day ;)
Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.have a nice day ;)

即使使用ctrl+c

,这也会重复10次或更多次

0 个答案:

没有答案