0

我有一个程序试图通过已实现的池使用创建和取消。

创作如下:

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( )。

但我不..

有人知道吗?

谢谢

4

1 回答 1

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

你已经st->t指向一个局部变量newThreadnewThread仅在当前循环迭代期间在范围内。在此迭代之后st->t将包含一个无效地址。

newThread位于堆栈上,因此在超出范围后,堆栈空间将用于其他变量。这在连续迭代中可能是不同pthread_t的,或者一旦循环结束,堆栈空间将用于完全不同类型的值。

要解决此问题,我可能会更改pthread_struct.t为 apthread_t而不是 a pthread_t *,然后将 pthread_create 调用更改为:

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

此外,st在调用pthread_create. 它可能应该在之后添加。就目前而言,线程池中有一个小窗口,st->t但尚未初始化。

于 2012-11-20T15:01:10.127 回答