volatile:防止编译器优化
代码:
1 #include<stdio.h> 2 #include<signal.h> 3 int a=0; 4 void signal_handler(int signal) 5 { 6 printf("signal is coming\n"); 7 a=1; 8 } 9 int main() 10 { 11 signal(2,signal_handler); 12 while(!a); 13 return 0; 14 15 }
结果:
[[email protected] SIGNAL]$ gcc -o thread_safety thread_safety.c -O3 [[email protected] SIGNAL]$ ./thread_safety ^Csignal is coming ^Csignal is coming ^\退出 (core dumped)
编译器优化,直接从寄存器取值,为了防止优化,采用sig_atomic_t类型与volatile限定符。
4 volatile int a=0; 或 4 volatile sig_atomic_t a=0; 结果: [[email protected] SIGNAL]$ gcc -o thread_safety thread_safety.c -O3 [[email protected] SIGNAL]$ ./thread_safety ^Csignal is coming
时间: 2024-10-12 21:00:28