在信号处理程序中修改全局变量时是否需要互斥锁
Is a mutex needed when modifying a global variable in a signal handler
在这种情况下是否需要 mutex
或某种同步
static int flag;
void sighandler(int sigid)
{
if (sigid != SIGINT)
return;
flag = 1;
}
int main(void)
{
if (signal(SIGINT, sighandler) == SIG_ERR)
return -1; /* cannot handle it ? */
while (flag == 0)
{
do_things();
}
return 0;
}
不,因为您没有在 flag
上执行读取-修改-写入。您应该将 flag
声明为 volatile static int flag
,以防止编译器将 while (flag == 0)
优化为 while (1)
。
不,互斥量在信号处理程序中是不必要的或不合适的。
在单线程的情况下,mutex是不需要的。是的,您希望您的旗帜是 volatile
, and (for non-trivial access) also sig_atomic_t
。但是,如果只有一个线程中断自身,您就不需要互斥体提供的内存防护语义。
相比之下,在多线程情况下,您确实拥有 cache coherency, re-ordering, and variable tearing that mutexes allay. However, no pthread mutex call is async-signal-safe, and thus a mutex cannot be safely manipulated from within a signal handler. You'll need to find another way to mix POSIX threads and signals 在这种情况下的所有顾虑。
在这种情况下是否需要 mutex
或某种同步
static int flag;
void sighandler(int sigid)
{
if (sigid != SIGINT)
return;
flag = 1;
}
int main(void)
{
if (signal(SIGINT, sighandler) == SIG_ERR)
return -1; /* cannot handle it ? */
while (flag == 0)
{
do_things();
}
return 0;
}
不,因为您没有在 flag
上执行读取-修改-写入。您应该将 flag
声明为 volatile static int flag
,以防止编译器将 while (flag == 0)
优化为 while (1)
。
不,互斥量在信号处理程序中是不必要的或不合适的。
在单线程的情况下,mutex是不需要的。是的,您希望您的旗帜是 volatile
, and (for non-trivial access) also sig_atomic_t
。但是,如果只有一个线程中断自身,您就不需要互斥体提供的内存防护语义。
相比之下,在多线程情况下,您确实拥有 cache coherency, re-ordering, and variable tearing that mutexes allay. However, no pthread mutex call is async-signal-safe, and thus a mutex cannot be safely manipulated from within a signal handler. You'll need to find another way to mix POSIX threads and signals 在这种情况下的所有顾虑。