在连接的线程上调用pthread_cancel会导致linux下的segfault [英] Calling pthread_cancel on a join'ed thread causes segfault under linux
问题描述
以下代码以第一次调用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]);
}
}
推荐答案
虽然实现可能具有在系统中唯一的线程ID,但应用程序应该只假设线程ID在单个进程中可用且唯一。调用POSIX.1-2008的本卷中定义的任何函数并作为参数传递来自另一个进程的线程的线程ID的效果未指定。如果使用detachstate属性设置为PTHREAD_CREATE_DETACHED或者为该线程调用pthread_detach()或pthread_join()创建线程ID,线程ID的生命周期将在线程终止之后结束。一个符合的实现可以在其生命周期结束后自由地重用一个线程ID。 如果应用程序尝试使用生命周期已结束的线程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().
您不能使用<$ 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!