pthread的 - 暂停/取消暂停所有主题 [英] pthread - Pausing/Unpausing all threads

查看:124
本文介绍了pthread的 - 暂停/取消暂停所有主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个暂停/取消暂停所有的线程在我的应用程序,这是由SIGUSR1(暂停)和SIGUSR2(取消暂停)激活。我想在条件我所有线程,并在接收信号时,可以使用调用pthread_cond_broadcast()使用调用pthread_cond_wait()的将挂在所有线程,但显然它不是安全使用调用pthread_cond_broadcast()信号处理...是否有任何替代解决这个问题(我必须避免忙等待)?

I'm trying to write a pause/unpause all threads in my application, which is activated by SIGUSR1 (pause) and SIGUSR2 (unpause). I thought of using pthread_cond_wait() in all threads and, when signal is received, use pthread_cond_broadcast() on conditional I would hang all threads on, but apparently it is not safe to use pthread_cond_broadcast() in signal handler... Is there any alternate solution to this problem (I must avoid busy wait)?

推荐答案

您可以使用专用线程使用的 调用sigwait。当接收到信号,等待返回,并给予线程可能会内通知其他线程的正常code 的(而不是一个信号处理器)。

You may use dedicated thread for wait signals using sigwait. When signal is received, waiting is returned, and given thread may inform other threads within normal code (not a signal handler).

假设你有暂停功能和取消暂停线程像这样

Assuming you have functions for pause and unpause threads like these

int paused;
pthread_mutex m;
pthread_cond cond;

void pause_threads(void)
{
    pthread_mutex_lock(&m);
    paused = 1;
    pthread_mutex_unlock(&m);        
}

void unpause_threads(void)
{
    pthread_mutex_lock(&m);
    paused = 0;
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&m);        
}

专用线程可以以这种方式来实现:

dedicated thread can be implemented in this way:

// Block signals for wait
sigset_t usr_set;

sigemptyset(&usr_set);
sigaddset(&usr_set, SIGUSR1);
sigaddset(&usr_set, SIGUSR2);
pthread_sigmask(SIG_BLOCK, &usr_set, NULL);

// If other threads will be created from given one, they will share signal handling.
// Otherwise actions above should be repeated for new threads.

int sig;
// Repeatedly wait for signals arriving.
while(!sigwait(&usr_set, &sig)) {
    if(sig == SIGUSR1) {
        pause_threads();
    }
    else {
        unpause_threads();
    }
}

这篇关于pthread的 - 暂停/取消暂停所有主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆