非法寻求pthread_cancel

Illegal Seek in pthread_cancel

本文关键字:cancel pthread 非法      更新时间:2023-10-16

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

创建如下:

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 索引中的线程?

而且我找不到任何关于非法寻求的信息。

感谢您的帮助

谢谢

问题是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 数组中,即使它实际上还不是线程。将插入逻辑放在调用 to 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锁中。