简体   繁体   English

在连接线程上调用pthread_cancel会导致linux下的segfault

[英]Calling pthread_cancel on a join'ed thread causes segfault under linux

The following code ends with a segmentation fault on the first call to pthread_cancel but only under linux. 以下代码以第一次调用pthread_cancel时的分段错误结束,但仅限于linux下。 Under Mac OS it runs fine. 在Mac OS下运行正常。 Am I not allowed to call pthread_cancel on a thread that has finished running? 我不允许在已经完成运行的线程上调用pthread_cancel吗? Maybe I should not call pthread_cancel at all? 也许我根本不应该打电话给pthread_cancel?

#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]);
    }
}

See POSIX XSH 2.9.2 : POSIX XSH 2.9.2

Although implementations may have thread IDs that are unique in a system, applications should only assume that thread IDs are usable and unique within a single process. 虽然实现可能具有系统中唯一的线程ID,但应用程序应该只假设线程ID在单个进程中可用且唯一。 The effect of calling any of the functions defined in this volume of POSIX.1-2008 and passing as an argument the thread ID of a thread from another process is unspecified. 调用此POSIX.1-2008卷中定义的任何函数并作为参数传递来自另一个进程的线程的线程ID的效果未指定。 The lifetime of a thread ID ends after the thread terminates if it was created with the detachstate attribute set to PTHREAD_CREATE_DETACHED or if pthread_detach() or pthread_join() has been called for that thread. 如果在将detachstate属性设置为PTHREAD_CREATE_DETACHED或者为该线程调用了pthread_detach()或pthread_join()的情况下创建线程,则线程ID终止后,线程ID的生命周期结束。 A conforming implementation is free to reuse a thread ID after its lifetime has ended. 符合性的实现可以在其生命周期结束后自由地重用线程ID。 If an application attempts to use a thread ID whose lifetime has ended, the behavior is undefined. 如果应用程序尝试使用其生命周期已结束的线程ID,则行为未定义。

If a thread is detached, its thread ID is invalid for use as an argument in a call to pthread_detach() or pthread_join(). 如果线程已分离,则其线程ID无效,无法用作对pthread_detach()或pthread_join()的调用中的参数。

You may not use a pthread_t after the thread it refers to has been joined, or if the thread has terminated while detached. 在引用的线程已加入后,或者如果线程在分离时已终止,则不能使用pthread_t Simply remove the pthread_cancel code from your program. 只需从程序中删除pthread_cancel代码即可。 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. pthread_cancel用于取消正在进行的线程,并且对于安全使用它而不会导致资源泄漏具有非常棘手的要求。 It's not useful for threads which exit on their own. 它对于自行退出的线程没有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM