开发者

Check thread status while leaving it in a waitable state

开发者 https://www.devze.com 2023-03-24 12:54 出处:网络
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

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 mul开发者_Python百科tithreaded program, therefore I cannot change the code of it. Also, I omitted this information as well but this is a Linux-based system.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号