2015-02-08 26 views
0
#include <stdio.h> 
#include <pthread.h> 
#include <signal.h> 

sigset_t set; 
int sigint_signal = 0; 
pthread_t monitor_thread, demo_thread; 
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; 

void *monitor() 
{ 

    while(1) 
    { 
     sigwait(&set, NULL); 
     pthread_mutex_lock(&m); 
     printf("__SIGINT received__\n"); 
     sigint_signal = 1; 
     pthread_cancel(demo_thread); 
     pthread_mutex_unlock(&m); 
    } 

} 

void *demo_function(){ 
    while(1){ 
     pthread_mutex_lock(&m); 
     fprintf(stdout, "__Value of SIGNAL FLAG %d:__\n",sigint_signal); 
     pthread_mutex_unlock(&m); 
    } 
    return NULL; 
} 

int main(){ 

    sigemptyset(&set); 
    sigaddset(&set,SIGINT); 
    pthread_sigmask(SIG_BLOCK,&set,0); 

    pthread_create(&monitor_thread, 0, monitor, NULL); 
    pthread_create(&demo_thread, 0, demo_function, NULL); 

    pthread_join(demo_thread, NULL); 
    return 0; 
} 

monitor_thread是連續運行趕上SIGINT信號線。接收到信號後,它必須取消另一個線程並結束。 SIGINT是越來越接收,這可以與可變sigint_signal成爲1一旦信號是received.But pthread_cancel是沒有得到執行,因爲一旦sigint_signal的值改變爲1,所述demo_thread繼續運行的值進行驗證。請幫忙。無法趕上SIGINT信號在多線程程序

+0

我用來編譯的命令是'gcc -g -Wall filename -o executable -lpthread'。 – 2015-02-08 05:07:25

+0

你真的不應該依賴'pthread_cancel'。您應該讓線程函數中的循環讀取由信號處理程序分配的變量,並在設置該變量時自行終止。 – 2015-02-08 05:11:22

+0

感謝@JohnZwinck,這個建議可行,但只是想問爲什麼不依靠pthread_cancel。 – 2015-02-08 05:23:50

回答

1

閱讀文檔:http://man7.org/linux/man-pages/man3/pthread_cancel.3.html

在那裏,你將看到pthread_cancel不保證瞬間幹掉線程,而是它取決於線程的狀態。默認情況下,取消只能在取消點進行,取消點包括write(),可能間接包括printf()

無論如何,真正的解決辦法是不使用pthread_cancel可言,而是在demo_function使用sigint_signal作爲while循環條件。

至於爲什麼pthread_cancel是一個壞主意,這是因爲一般來說,函數通常不會以他們準備死亡的方式編寫。在執行可能異步終止的上下文中很難推斷資源管理。