我在 Linux 中有一个“C”应用程序,其中我注册了 SIGALRM 处理程序。我的 SIGALRM 处理程序更新其他线程也在访问的一些全局数据。要求:为了保护全局数据,我需要在线程内访问信号时完全阻止信号。所以我需要一种方法来实现它。问题:我无法完全阻止信号。sigprocmask 不工作。尽管如果 main 是唯一正在运行的线程,它会阻塞信号。但是当多个线程运行时,SIGALRM 不断出现。我已经测试了 pthread_sigmask 但仅更新当前线程的信号掩码。
添加代码逻辑:
sig_atomic_t atm_var;
void signal_handler()
{
atm_var++;
}
void thread_func()
{
pthread_sigmask(UNBLOCK,...);
while(1)
{
/* some stuff */
pthread_sigmask(BLOCK,...);
/* critical section, can easily access or modify atm_var */
pthread_sigmask(UNBLOCK,...);
}
}
int main()
{
sigprocmask(BLOCK,...);
pthread_create(...,thread_func,...);
sigaction(SIGALRM,...);
setitimer(ITIMER_REAL,...);
while(1)
{
}
}
Run Code Online (Sandbox Code Playgroud)
再补充一点:在主线程或其他线程中修改 sig_atomic_t 变量(信号处理程序正在修改)有多安全?
或者
当我修改主线程或其他线程内的 sig_atomic_t 变量时,不阻止信号是安全的做法吗?