我有一个在C中使用ao_lib播放mp3的线程。我需要通过播放中途跳到下一个mp3,所以在创建播放mp3的线程后,我试图创建另一个等待的线程用户输入一个角色,如果第一个在第二个之前加入,那么第二个也被杀死。
main()
{
ret1 = pthread_create(&thread1, NULL, func_play, (void *) url);
ret2 = pthread_create(&thread2, NULL, func_char, NULL);
/* I need to somehow do something here to break func_play if a user
enters a specific char in func_char */
pthread_join(thread1, NULL);
pthread_cancel(thread2);
return 0;
}
那不起作用。任何解决方案都会非常受欢迎。
由于
答案 0 :(得分:1)
这将是我认为可行的模式,我不知道 mp3 播放功能是如何工作的,但你需要它是非阻塞的,也许是读取 .mp3 文件并以块的形式播放,因此您可以使用类似的东西打破主循环(_循环播放 .mp3 )
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
static pthread_mutex_t mutex;
struct SharedData
{
const char *url;
int stop;
int ready;
};
void *
mainloop(void *data)
{
struct SharedData *sharedData;
int ready;
int stop;
sharedData = data;
if (sharedData == NULL)
return NULL;
stop = 0;
ready = 0;
while (ready == 0)
{
pthread_mutex_lock(&mutex);
ready = sharedData->ready;
pthread_mutex_unlock(&mutex);
usleep(1000);
}
while (stop == 0)
{
pthread_mutex_lock(&mutex);
stop = sharedData->stop;
pthread_mutex_unlock(&mutex);
printf(".");
fflush(stdout);
sleep(1);
}
return NULL;
}
void *
controlthread(void *data)
{
int chr;
struct SharedData *sharedData;
sharedData = data;
if (sharedData == NULL)
return NULL;
pthread_mutex_lock(&mutex);
sharedData->ready = 1;
pthread_mutex_unlock(&mutex);
printf("Press return to stop the main loop...\n");
while (((chr = getchar()) != EOF) && (chr != '\n'))
usleep(1000);
pthread_mutex_lock(&mutex);
sharedData->stop = 1;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main(void)
{
struct SharedData data;
pthread_t threads[2];
pthread_mutex_init(&mutex, NULL);
memset(&data, 0, sizeof(data));
pthread_create(&threads[0], NULL, mainloop, &data);
pthread_create(&threads[1], NULL, controlthread, &data);
pthread_join(threads[0], NULL);
return 0;
}