检查线程状态,同时使其处于等待状态 [英] Check thread status while leaving it in a waitable state

查看:123
本文介绍了检查线程状态,同时使其处于等待状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以检查线程的状态,该线程可能处于等待状态,而不必处于等待状态,并且是否处于等待状态,我想将其保持在该状态.

I am wondering if it is possible to check the status of a thread, which could possibly be in a waitable state but doesn't have to be and if it is in a waitable state I would like to leave it in that state.

基本上,如何在不更改其(等待)状态的情况下检查线程的状态.

Basically, how can I check the status of a thread without changing its (waitable) state.

通过等待,我的意思是,如果我调用wait(pid),它将正确返回并且不会挂起.

By waitable, I mean if I called wait(pid) it would return properly and not hang.

让我也补充一点,我正在跟踪一个多线程程序,因此我无法更改其代码.另外,我也省略了此信息,但这是一个基于Linux的系统.

Let me also add that I am tracing a multithreaded program, therefore I cannot change the code of it. Also, I omitted this information as well but this is a Linux-based system.

推荐答案

您在询问进程或线程吗? wait函数作用于进程,而不是线程,因此您编写的问题无效.

Are you asking about processes or threads? The wait function acts on processes, not threads, so your question as-written is not valid.

对于(子)进程,您可以通过使用WNOWAIT标志调用waitid来检查状态.这将使进程处于等待状态.

For (child) processes, you can check the state by calling waitid with the WNOWAIT flag. This will leave the process in a waitable state.

对于线程,在某些实现上,您可以调用pthread_kill(thread, 0)并检查ESRCH以确定线程是否退出,而将thread保留为可连接状态.请注意,仅在线程可连接时有效.如果它已分离或已经加入,则您正在调用未定义行为",并且程序应崩溃或恶化.不幸的是,在这种情况下,不要求pthread_kill报告ESRCH,因此,当它实际上已经终止时,它可能会错误地报告一个线程仍然存在.当然,在pthread_exit调用和实际终止之间永远存在的线程与实际上已经终止的线程之间,在形式上没有没有区别.因此,这个问题有点毫无意义.换句话说,没有要求可连接线程永远终止,直到pthread_join被阻止等待终止.

For threads, on some implementatiosn you can call pthread_kill(thread, 0) and check for ESRCH to determine if the thread has exited or not, while leaving thread in a joinable state. Note that this is valid only if the thread is joinable. If it was detached or already joined, you are invoking Undefined Behavior and your program should crash or worse. Unfortunately, there is no requirement that pthread_kill report ESRCH in this case, so it might falsely report that a thread still exists when in fact it already terminated. Of course, formally there is no difference between a thread that's sitting around forever between the call to pthread_exit and actual termination, and a thread that has actually finished terminating, so the question is a bit meaningless. In other words, there's no requirement that a joinable thread ever terminate until pthread_join is blocked waiting for it to terminate.

这篇关于检查线程状态,同时使其处于等待状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆