qiu*_*bit 2 c conditional multithreading pthreads
我试图在我的应用程序中编写一个暂停/取消暂停所有线程,这由SIGUSR1(暂停)和SIGUSR2(取消暂停)激活。我想到要pthread_cond_wait()在所有线程中使用,并且在接收到信号时,pthread_cond_broadcast()在有条件的情况下使用我会挂起所有线程,但是显然pthread_cond_broadcast()在信号处理程序中使用它是不安全的...是否有其他替代方法可以解决此问题(我必须避免忙等)?
您可以使用sigwait将专用线程用于等待信号。接收到信号后,将返回等待状态,并且给定线程可以在正常代码(不是信号处理程序)内通知其他线程。
假设您具有暂停和取消暂停这样的线程的功能
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);
}
Run Code Online (Sandbox Code Playgroud)
专用线程可以通过以下方式实现:
// 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();
}
}
Run Code Online (Sandbox Code Playgroud)