在使用带有信号处理程序的multithreading程序时,有没有办法确保primefaces性?

如果我有这样的程序(伪代码):

mutex_lock; func() { lock(mutex_lock); // Some code (long enough to make a // race condition if no proper synchronisation // is available). We also going to call a signal, // say, SIGINT, through (ctrl-c), while we are in // the range of locking and unlocking the lock. unlock(mutex_lock); } sig_handler_func(sig) { // Say, we are handling SIGINT (ctrl-c) signal // And we need to call func from here too. if (sig == SIGINT) { func(); } } main() { // Calling func from main func(); } 

然后在尝试获取func中的锁时会出现死锁,而它已经从“主”调用者获取。 我想知道是否有办法暂停C语言中的信号处理,特别是在这个例子中输入func并获取锁定,并恢复信号处理并在退出func时调用处理程序。

你想要pthread_sigmasksigprocmask的multithreading版本

这是一些示例伪代码:

 int main(void) { sigset_t omask; sigset_t nmask; // add as many signals as you want to the mask ... sigemptyset(&nmask); sigaddset(&nmask,SIGINT); // [temporarily] block signals pthread_sigmask(SIG_BLOCK,&nmask,&omask); // call function safely func(); // restore signal mask pthread_sigmask(SIG_SETMASK,&omask,NULL); // pending signals should occur now ... } 

我不完全确定,但是,您可能需要使用pthread_sigmask来阻止除一个线程之外的所有线程中的信号,并且仅从该线程执行上述操作。

另外,如果我没有说我会重构你的代码,那将是我的疏忽。 你可以在信号处理程序中做的事情[除此之外]是有限的(例如没有malloc ,没有printf等)

专用于一个线程进行信号处理并使其执行sigsetjmp ,信号处理程序执行siglongjmp

或者让信号处理程序设置一个在基本级别监视的volatile全局(例如signal_occurred )。

因此,您在信号处理程序中执行的所有“繁重工作”都可以从基本任务级别完成,您可以在其中执行任何操作。

你需要两个锁。 在你的func()使用的那个,以及一个用来保护进程的信号掩码。

您还必须对信号primefaces进行屏蔽和取消屏蔽:

 static pthread_mutex_t mask_mutex = PTHREAD_MUTEX_INITIALIZER; sigset_t old_set; sigset_t new_set; sigemptyset( &new_set ); sigaddset( &new_set, SIGINT ); pthread_mutex_lock( &mask_mutex ); pthread_sigmask( SIG_BLOCK, &new_mask, &old_mask ); func(); pthread_sigmask( SIG_SETMASK, &old_mask, NULL ); pthread_mutex_unlock( &mask_mutex ); 

由于pthread_sigmask()没有锁定,因此执行重叠时线程可能会破坏进程sigmask。

在这种不确定的情况下,您可以使用测试互斥函数(trylock),以确保安全。 有了这个,你也不一定需要阻止。