【问题标题】:Pause/Resume another thread暂停/恢复另一个线程
【发布时间】:2011-10-18 11:35:10
【问题描述】:

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

【问题讨论】:

标签: c pthreads


【解决方案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 机制 - 然后您可以在此基础上实现暂停和恢复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    相关资源
    最近更新 更多