2012-11-20 43 views
0

我有一個程序嘗試使用create和cancel來通過已實現的池。pthread_cancel總是崩潰

創建如下:

while (created<threadsNum){ 
    pthread_t newThread; 
    pthread_struct *st; //Open the thread that handle the deleting of the sessions timeout. 
    st = (pthread_struct*)malloc(sizeof(pthread_struct)); 
    st->id = created; 
    st->t = &newThread; 
    pthread_mutex_lock(&mutex_threadsPool); 
    readingThreadsPool[created] = st; 
    pthread_mutex_unlock(&mutex_threadsPool); 
     if((threadRes1 = pthread_create(&newThread, NULL, pcapReadingThread, (void*)created))) 
     { 
     syslog(LOG_CRIT, "Creating Pcap-Reading Thread %d failed.",created); 
       printf("Creating Pcap-Reading Thread %d failed.\n",created); 
       exit(1); 
     } 
    syslog(LOG_INFO, "Created Pcap-Reading Thread %d Successfully.",created); 
    created++; 
} 

後來我嘗試取消它們並重啓:

pthread_t* t; 
pthread_struct* tstr; 
int i; 
pthread_mutex_unlock(&mutex_threadsPool); 
//first go on array and kill all threads 
for(i = 0; i<threadsNum ; i++){ 
    tstr = readingThreadsPool[i]; 
    if (tstr!=NULL){ 
     t = tstr->t; 
        //Reaches here :-) 
     if (pthread_cancel(*t)!=0){ 
      perror("ERROR : Could not kill thread"); 
     } 
     else{ 
      printf("Killed Thread %d \n",i); 
     } 
        //doesnt reach here 

    } 
} 

我檢查在創建線程的內存地址中的第一部分和地址的第二部分即將被取消的線程..他們匹配.. 我讀過關於線程管理器,如果有人叫killall()不能工作。

但我不..

任何人有什麼想法?

感謝

+0

這不是C嗎?我在發佈的代碼中沒有看到特定的C++。 – hmjd

回答

1
while (created<threadsNum){ 
    pthread_t newThread; 
    pthread_struct *st; 
    /* ... */ 
    st->t = &newThread; 
    /* ... */ 
} 

你得st->t指向一個局部變量newThreadnewThread僅在當前循環迭代期間處於範圍內。在此迭代之後,st->t將包含無效地址。

newThread在堆棧中,所以在超出範圍之後堆棧空間將用於其他變量。在連續的迭代中,這可能與pthread_t不同,或者一旦循環結束,那麼堆棧空間將用於完全不同類型的值。

爲了解決這個問題,我可能會改變pthread_struct.t是一個pthread_t,而不是pthread_t *,然後更改在pthread_create調用:

pthread_create(&st->t, /*...*/) 

此外,你應該小心添加st線程池在撥打pthread_create之前。它應該可能在之後添加。現在,有一個小窗口,st->t位於線程池中,但尚未初始化。

+0

@約翰,我只是做了..但是現在,在成功創建10個線程之後,0索引中的線程獲得了 「無法殺死線程:非法查找」 並且線程1-9被取消成功...您是否有任何想法爲什麼第一個沒有取消? –

+0

通過說「做了那個」我的意思是我改變了st->是一個線程而不是指針。 –