如何查询 pthread 以查看它是否仍在运行? [英] How do you query a pthread to see if it is still running?
问题描述
在我的析构函数中,我想干净地销毁一个线程.
我的目标是等待一个线程完成执行,然后销毁该线程.
我发现关于查询 pthread 状态的唯一方法是 pthread_attr_setdetachstate 但这只会告诉您您的主题是否是:
- PTHREAD_CREATE_DETACHED
- PTHREAD_CREATE_JOINABLE
这两者都与线程是否仍在运行无关.
如何查询 pthread 以查看它是否仍在运行?
听起来您在这里有两个问题:
我怎样才能等到我的线程完成?
答案:这是pthreads直接支持的——让你的待停止线程JOINABLE(当它第一次启动时),并使用pthread_join()阻塞你当前的线程,直到待停止线程不再运行.
<小时>如何判断我的线程是否仍在运行?
答案:你可以添加一个thread_complete"标志来实现:
场景:线程 A 想知道线程 B 是否还活着.
当线程 B 被创建时,它被赋予一个指向thread_complete"标志地址的指针.在创建线程之前,thread_complete"标志应该被初始化为 NOT_COMPLETED.线程 B 的入口点函数应立即调用 pthread_cleanup_push() 以推送清理处理程序",该处理程序将thread_complete"标志设置为 COMPLETED.
在此处查看有关清理处理程序的详细信息:pthread 清理处理程序>
您需要包含相应的 pthread_cleanup_pop(1) 调用,以确保无论发生什么情况(即,如果线程正常退出或由于取消等原因),都会调用清理处理程序.
然后,线程 A 可以简单地检查thread_complete"标志以查看线程 B 是否已经退出.
注意:你的thread_complete"标志应该被声明为volatile"并且应该是一个原子类型——GNU编译器为此提供了sig_atomic_t.这允许两个线程一致地访问相同的数据,而无需同步构造(互斥体/信号量).
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.
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.
How do you query a pthread to see if it is still running?
It sounds like you have two questions here:
How can I wait until my thread completes?
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.
How can I tell if my thread is still running?
Answer: You can add a "thread_complete" flag to do the trick:
Scenario: Thread A wants to know if Thread B is still alive.
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.
See details about cleanup handlers here: pthread cleanup handlers
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.).
Then, Thread A can simply check the "thread_complete" flag to see if Thread B has exited yet.
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屋!