暂停/恢复另一个线程

时间:2011-10-18 11:35:11

标签: c pthreads

我知道mutex可以是一个实现,但是我想知道有一种方法可以暂停/恢复另一个线程,就像在视频播放中一样。当另一个正在运行的线程很复杂时,这种方法更容易编程。

1 个答案:

答案 0 :(得分:1)

SIGTSTP,暂停进程的信号,如果你有两个进程可以使用,但信号有几个缺点,所以我不建议使用它们。对于受控制的稳定方法,您必须使用互斥锁自行完成,其中用户暂停播放会导致锁定互斥锁,执行播放的线程会尝试锁定互斥锁。像这样:

static pthread_mutex_t mutex;

/* UI thread */
void g(void)
{
    while(1) {
        get_input();
        if(user_wants_to_pause)
            pthread_mutex_lock(&mutex);
        else if(user_wants_to_resume)
            pthread_mutex_unlock(&mutex);
    }
}

/* rendering thread */
void f(void)
{
    while(1) {
        pthread_mutex_lock(&mutex);
        /* if we get here, the user hasn't paused */
        pthread_mutex_unlock(&mutex);
        render_next_frame();
    }
}

如果您需要在两个线程之间进行更多通信,则可以使用标准IPC机制(如管道) - 然后您可以实现暂停和恢复。

相关问题