我想确定特定线程是否“存在”。
pthread_kill()似乎适合这项任务,至少根据其手册页来看是这样。
如果sig为0,则不发送信号,但仍执行错误检查。
或者,正如我的系统手册页所述:
如果sig为0,则不发送信号,但仍进行错误检查;这可用于检查线程 ID 是否存在。
但是,当我尝试传入未初始化的 时pthread_t,应用程序总是出现 SEGFAULT。
深入研究这一点,pthread_kill.c(来自我的工具链)的以下代码片段似乎没有进行错误检查,只是尝试取消引用threadid(取消引用位于pd->tid)。
int
__pthread_kill (threadid, signo)
pthread_t threadid;
int signo;
{
struct pthread *pd = (struct pthread *) threadid;
/* Make sure the descriptor is valid. */
if (DEBUGGING_P && INVALID_TD_P (pd))
/* Not a valid thread handle. */
return ESRCH;
/* Force load of pd->tid into local variable or register. Otherwise
if a thread exits between ESRCH …Run Code Online (Sandbox Code Playgroud) 以下代码在第一次调用 pthread_cancel 时以分段错误结束,但仅限在 Linux 下。Mac OS 下运行良好。我是否不允许在已完成运行的线程上调用 pthread_cancel ?也许我根本不应该调用 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]);
}
}
Run Code Online (Sandbox Code Playgroud)