【发布时间】:2014-03-27 04:12:55
【问题描述】:
我有 2 个线程(线程 1 和线程 2)。我对SIGINT 有信号处理。每当SIGINT 发生时,线程2 应该处理该信号。为此我写了下面的程序
void sig_hand(int no) //signal handler
{
printf("handler executing...\n");
getchar();
}
void* thread1(void *arg1) //thread1
{
while(1) {
printf("thread1 active\n");
sleep(1);
}
}
void * thread2(void * arg2) //thread2
{
signal(2, sig_hand);
while(1) {
printf("thread2 active\n");
sleep(3);
}
}
int main()
{
pthread_t t1;
pthread_t t1;
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
while(1);
}
我编译并运行了程序。每 1 秒“thread1 active”正在打印,每 3 秒“thread2 active”正在打印。
现在我生成了SIGINT。但它的打印“thread1 active”和“thread2 active”消息如上所示。我再次生成了SIGINT,现在每 3 秒只打印一次“thread2 active”消息。我再次生成了SIGINT,现在所有线程都被阻塞了。
所以我明白了,第一次主线程执行信号处理程序。第二次thread1执行handler,最后thread2执行signal handler。
我如何编写代码,例如每当信号发生时,只有 thread2 必须执行我的信号处理程序?
【问题讨论】:
-
printf不是异步安全库调用,这意味着它不能由信号处理程序调用...如果是,则行为未指定(可能会发生坏事)。就此而言,getchar也不是异步安全的。
标签: c linux multithreading pthreads signals