Check thread status while leaving it in a waitable state

随声附和 提交于 2019-12-10 21:18:22

问题


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.

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

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.


回答1:


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

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

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.




回答2:


Do you want to do something like this (pseudo-code)?

if (status(my_thread) == waiting)
    do_something();
else
    do_something_else();

If that is indeed what you are trying to do, you are exposing yourself to race conditions. For example, what if my_thread wakes up after status(my_thread) but before do_something() (or even before == waiting)?

You might want to consider condition variables for safely communicating "status" between threads. Thread-safe queue might also be an option...

BTW, Lawrence Livermore National Laboratory has an excellent tutorial on multithreading concepts at https://computing.llnl.gov/tutorials/pthreads/ (including condition variables). This particular document uses POSIX API, but concepts that are explained are universal.



来源:https://stackoverflow.com/questions/6880301/check-thread-status-while-leaving-it-in-a-waitable-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!