如何确定分离的 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/