pthread - 暂停/取消暂停所有线程 [英] pthread - Pausing/Unpausing all threads

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

问题描述

我正在尝试在我的应用程序中编写暂停/取消暂停所有线程,该线程由 SIGUSR1(暂停)和 SIGUSR2(取消暂停)激活.我想在所有线程中使用 pthread_cond_wait() ,当收到信号时,有条件地使用 pthread_cond_broadcast() 我会挂起所有线程,但显然它不安全在信号处理程序中使用 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.当接收到信号时,将返回等待,并且给定线程可能会在普通代码(不是信号处理程序)中通知其他线程.

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天全站免登陆