你如何查询pthread的,看它是否仍在运行? [英] How do you query a pthread to see if it is still running?
问题描述
在我的析构函数我要干净摧毁一个线程。
In my destructor I want to destroy a thread cleanly.
我的目标是要等待一个线程执行完,然后销毁线程。
My goal is to wait for a thread to finish executing and THEN destroy the thread.
我发现了大约一个查询的pthread状态的唯一事情是<一个href=\"https://computing.llnl.gov/tutorials/pthreads/man/pthread_attr_getdetachstate.txt\">pthread_attr_setdetachstate但这只是告诉你,如果你的线程是:
The only thing I found about querying the state of a pthread is pthread_attr_setdetachstate but this only tells you if your thread is:
- PTHREAD_CREATE_DETACHED
- PTHREAD_CREATE_JOINABLE
这两项都无关线程是否仍在运行与否。
Both of those have nothing to do with whether the thread is still running or not.
如何查询pthread的,看它是否仍在运行?
推荐答案
这听起来像你这里有两个问题:
It sounds like you have two questions here:
答:这是直接由pthreads的支持 - 让你的线程要被停止可连接(当它第一次启动),并使用在pthread_join()来阻止您当前线程,直到线程要被停止不再运行。
Answer: This is directly supported by pthreads -- make your thread-to-be-stopped JOINABLE (when it is first started), and use pthread_join() to block your current thread until the thread-to-be-stopped is no longer running.
答:您可以添加一个thread_complete标志做的伎俩:
Answer: You can add a "thread_complete" flag to do the trick:
场景:线程A想知道,如果线程B还活着。
Scenario: Thread A wants to know if Thread B is still alive.
当创建线程B,它被赋予一个指针thread_complete标记地址。在创建线程之前的thread_complete标志应被初始化为NOT_COMPLETED。线程B的入口点函数应该立即调用pthread_cleanup_push()推动了清理处理程序,它设置了thread_complete标记为已完成。
When Thread B is created, it is given a pointer to the "thread_complete" flag address. The "thread_complete" flag should be initialized to NOT_COMPLETED before the thread is created. Thread B's entry point function should immediately call pthread_cleanup_push() to push a "cleanup handler" which sets the "thread_complete" flag to COMPLETED.
请参阅这里清理处理程序的详细信息: pthread的清除处理程序
See details about cleanup handlers here: pthread cleanup handlers
您将需要包括相应的pthread_cleanup_pop(1)调用,以确保清理处理程序被调用无论什么(即如果线程正常退出或由于取消,等等)。
You'll want to include a corresponding pthread_cleanup_pop(1) call to ensure that the cleanup handler gets called no matter what (i.e. if the thread exits normally OR due to cancellation, etc.).
然后,线程A可以简单地检查thread_complete标志来判断是否线程B已退出呢。
Then, Thread A can simply check the "thread_complete" flag to see if Thread B has exited yet.
注:您的thread_complete标志应宣布为动荡,应该是一个原子类型 - GNU编译器为此提供了sig_atomic_t。这允许两个线程一致访问相同的数据,而无需同步结构(互斥/信号灯)。
NOTE: Your "thread_complete" flag should be declared "volatile" and should be an atomic type -- the GNU compilers provide the sig_atomic_t for this purpose. This allows the two threads consistent access the same data without the need for synchronization constructs (mutexes/semaphores).
这篇关于你如何查询pthread的,看它是否仍在运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!