linux - 如何确定分离的 pthread 是否存活?

标签 linux pthreads

如何确定分离的 pthread 是否仍然事件

我有一个与线程的通信 channel (一个从线程向外指向的单向队列)但是如果线程死了会发生什么?

我应该放弃使用进程信号还是可以探测以某种方式了解线程的活跃度?

最佳答案

对于可连接的(即不分离的)pthread,您可以使用 pthread_kill像这样:

int ret = pthread_kill(YOUR_PTHREAD_ID, 0);

如果您得到一个 ESRCH 值,则可能是您的线程已死。

然而,这不适用于分离的 pthreads,因为在它结束后,它的线程 ID 可以被另一个线程重用。

来自评论:

The answer is wrong because if the thread is detached and is not alive, the pthread_t is invalid. You can't pass it to pthread_kill. It could, for example, be a pointer to a structure that was freed, causing your program to crash. POSIX says, "A conforming implementation is free to reuse a thread ID after its lifetime has ended. If an application attempts to use a thread ID whose lifetime has ended, the behavior is undefined." – Thanks @DavidSchwartz

关于linux - 如何确定分离的 pthread 是否存活?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1693180/

相关文章:

c++ - 你如何确保对 C++20 的支持?

linux - Qt版本无效

linux - VirtualBox 警告 : program compiled against libxml 209 using older 207

c - 从 pthread 到 main 的信号

linux - 如何使用克隆系统调用分配新的 TLS 区域

linux - Spyder:变量资源管理器不显示连接的远程内核的变量

linux - 在 64 位 Linux 上执行 32 位二进制文​​件时的 SIGSEGV

c++ - 从 C++ "time.h"测量的运行时间是实际运行时间的两倍

c - pcap中不同线程中的数据包处理程序

c - 当获取它的线程退出时,Mutex 会发生什么?