簡體   English   中英

在pthread_cancel中非法尋求

[英]Illegal Seek in 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索引中的線程?

而且我找不到關於非法尋求的任何信息。

謝謝您的幫助

謝謝

問題是在初始化之前正在使用newThread

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

但是在成功調用pthread_create()之后, newThread不會接收到值。 看來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並期望readingThreadsPool輸入一個條目(我認為可能是由於created傳遞而導致的情況),然后將pthread_create()封裝在mutex_threadsPool鎖內。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM