2012-11-20 73 views
0

我有一個程序試圖使用創建和取消通過實施的池。非法尋求pthread_cancel

創建如下:

int threadsNum=10; 
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; 
     if (pthread_cancel(t)!=0){ 
      perror("ERROR : Could not kill thread"); 
     } 
     else{ 
      printf("Killed Thread %d \n",i); 
     } 
    } 
} 

到目前爲止好,但唯一的問題是,輸出 錯誤:無法殺死線程:非法查詢 殺死線程1

死亡線程2

殺死線程3

殺螺紋4

殺螺紋5

殺螺紋6

殺螺紋7

殺螺紋8

殺螺紋9

爲什麼它不殺死0索引中的線程?

我找不到任何有關非法追求任何東西..

感謝您的幫助人們

感謝

回答

1

的問題是,它被初始化之前newThread正在使用:

pthread_t newThread; 
pthread_struct *st; 
st = (pthread_struct*)malloc(sizeof(pthread_struct)); 
st->id = created; 
st->t = newThread; 

newThread在成功調用pthread_create()之後才收到值。看來newThread變量在循環的後續迭代中保留其先前的值,這導致除了最後的線程被啓動之外的所有線程的正確取消,因爲其ID從未被插入到readingThreadsPool陣列中。

您需要在致電pthread_create()後填寫st->t成員。

由於目前的代碼,可以將條目插入到readingThreadsPool數組中,儘管它實際上並不是一個線程。將插入邏輯,來電後pthread_create()

if((threadRes1 = 
     pthread_create(&(st->t), 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); 
} 
pthread_mutex_lock(&mutex_threadsPool); 
readingThreadsPool[created] = st; 
pthread_mutex_unlock(&mutex_threadsPool); 

,或者如果pcapReadingThread()函數訪問readingThreadsPool,並希望爲自己的條目(我認爲可能是由於created傳遞的情況下),然後附上pthread_create()裏面鎖的mutex_threadsPool