我有2个线程(thread1和thread2).我有信号处理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);
}
Run Code Online (Sandbox Code Playgroud)
我编译并运行该程序.每1秒"thread1 active"正在打印,并且每3秒"thread2 active"正在打印.
现在我生成了SIGINT.但它上面打印"thread1 active"和"thread2 active"消息.我再次生成SIGINT,现在每3秒只有"thread2 active"消息正在打印.我再次生成SIGINT,现在所有线程都被阻止了.
所以我理解,第一次主线程执行信号处理程序.第二次thread1执行处理程序,最后thread2执行信号处理程序.
我怎样才能编写代码,就像信号发生时一样,只有thread2必须执行我的信号处理程序?