本文介绍了在连接的线程上调用pthread_cancel会导致linux下的segfault的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码以第一次调用pthread_cancel时的分段错误结束,但仅在linux下。在Mac OS下运行正常。我不允许在已经运行的线程上调用pthread_cancel?也许我不应该调用pthread_cancel?

The following code ends with a segmentation fault on the first call to pthread_cancel but only under linux. Under Mac OS it runs fine. Am I not allowed to call pthread_cancel on a thread that has finished running? Maybe I should not call pthread_cancel at all?

#include <iostream>
#include <pthread.h>

using namespace std;


void* run(void *args) {
   cerr << "Hallo, Running" << endl;
}

int main() {
    int n = 100;
    pthread_t* pool = new pthread_t[n];

    for(int i=0;i<n;i++) {
        pthread_t tmp;
        pthread_create(&tmp,NULL,&run,NULL);
        pool[i] = (tmp);
    }

    for(int i=0;i<n;i++) {
        pthread_join(pool[i],0);
    }

    for(int i=0;i<n;i++) {
        pthread_cancel(pool[i]);
    }
}


推荐答案

如果线程脱离,

If a thread is detached, its thread ID is invalid for use as an argument in a call to pthread_detach() or pthread_join().

您不能使用<$ c键来调用pthread_detach()或pthread_join $ c> pthread_t 之后,它所引用的线程已经加入,或者如果线程已经终止,而分离。只需从程序中删除 pthread_cancel 代码即可。这是不对的。 pthread_cancel 是用于取消正在进行的线程,并且对安全使用它有非常棘手的要求,而不会导致资源泄漏。这对于自己退出的线程没有用。

You may not use a pthread_t after the thread it refers to has been joined, or if the thread has terminated while detached. Simply remove the pthread_cancel code from your program. It's wrong. pthread_cancel is for cancelling an in-progress thread, and has very tricky requirements for using it safely without causing resource leaks. It's not useful for threads which exit on their own.

这篇关于在连接的线程上调用pthread_cancel会导致linux下的segfault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:03
查看更多