2012-11-20 93 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->是一个线程而不是指针。 –