非法寻求pthread_cancel

时间:2012-11-20 16:02:35

标签: c++ linux pthreads

我有一个程序试图通过实现的池使用create和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

Killed Thread 4

杀死线程5

杀死线程6

杀死线程7

杀死线程8

杀死线程9

为什么它也不会杀死0索引中的线程?

我无法找到关于非法寻求的任何事情......

感谢您的帮助

由于

1 个答案:

答案 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数组中。

您需要在致电st->t后填充pthread_create()成员。

正如代码当前所示,即使条目尚未成为线程,也可以将条目插入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的锁内。