取消信号处理程序中的线程

我已经启动了一个计时器,并将间隔设置为5秒,并为其注册一个信号处理程序。 当遇到SIGALRM试图终止在信号处理程序内的线程,BT不能做到这一点。 线程没有被终止,而是整个过程被终止。
以下是代码:

void signalHandler() { printf("Caught signal ...\n"); printf("Now going to terminate thread..\n"); pthread_kill(tid, SIGKILL); } void * thread_function() { int oldstate; char result[256] = {0}; time_t startTime = time(NULL); time_t timerDuration = 5; time_t endTime = startTime + timerDuration; while(1) { printf("Timer is runnuing as dameon..\n"); if(!strcmp(result, "CONNECTED")) { resp = 1; pthread_exit(&resp); } } } int main() { int *ptr[2]; signal(SIGALRM, signalHandler); timer.it_interval.tv_usec = 0; timer.it_interval. tv_usec = 0; timer.it_value.tv_sec = INTERVAL; timer.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &timer, 0); pthread_create(&tid, NULL, thread_function, NULL); pthread_join(tid, (void**)&(ptr[0])); printf("test %d\n\n",*ptr[0]); while(1) printf("1"); } 

平台:Linux,gcc编译器

据我所知,你几乎不能调用信号处理程序内的任何东西,因为你不知道你的代码是在什么状态。

你最好的选择是建立一个线程来处理你的信号。 所有其他线程应该调用pthread_setsigmask并阻塞所有信号,然后创建另一个线程,该线程调用pthread_setsigmask来捕获SIGALARM ,然后调用sigwait ,此时可以取消另一个线程。

与单线程环境相比,在多线程环境下处理信号的方式有很大不同。 在一个多线程的代码中,你应该阻塞所有具有业务逻辑的线程的所有信号,然后创建一个单独的线程来处理信号。 这是因为,在多线程环境中,不能确定信号将传递到哪个线程。

请参阅此链接了解更多详情:
http://devcry.heiho.net/2009/05/pthreads-and-unix-signals.html

除此之外,杀死一个线程使用pthread_cancel应该适合你。

你可以尝试使用一个标志:

 int go_on[number_of_threads] = { 1 }; void signalHandler() { printf("Caught signal ...\n"); printf("Now going to terminate thread..\n"); go_on[tid] = 0; } void * thread_function() { /* */ while(go_on[this_thread_id]) { printf("Timer is runnuing as dameon..\n"); if(!strcmp(result, "CONNECTED")) { resp = 1; pthread_exit(&resp); } } }