从多线程应用程序有效退出(详细信息) [英] Efficient exit from multithreaded application (specifics)
问题描述
我已经阅读了一些有关将消息从一个线程冒泡到所有其他线程以正常退出的正确方法的资料(每个线程都执行它自己的退出例程).其中,我喜欢可以从任何线程进行标记的全局原子布尔值的想法,所有其他线程都检查该标记以执行退出例程-当所有线程都加入后,主线程便可以退出应用程序.>
计算线程的处理方式可能会完全不同,对吧?
这有效且安全吗?有更好的方法吗?
谢谢!
在Windows中,我使用QueueUserAPC调用引发异常的函数,导致线程干净退出.
我在这里在这个答案中写了更多有关细节的信息:
总而言之,这是发生了什么:
说线程A要终止线程B(然后终止C,D ...)
- 线程A调用
QueueUserAPC()
,将句柄传递给线程B和函数的地址,这将引发类MyThreadExit的异常. - 线程B正常运行,直到它调用检查可警报等待的内容为止.也许
WaitForSingleObjectEx
,也许SleepEx
或其他. - 这时,线程B运行先前传递的APC函数,从而导致异常在线程B中引发.
- 所有分配给堆栈的对象都会自动正确地销毁,因为异常会使线程B展开"其堆栈.
- 线程B的最外层线程函数将捕获该异常.
- 线程B现在退出,可能向线程A发出信号通知它已完成.
I've read a few sources on proper methods of bubbling a message out from a thread to all other threads to exit gracefully (every thread performs it's own exit routine). Of these, I liked the idea of a global atomic boolean that can be flagged from any thread, and all other threads check this flag to perform an exit routine - when all threads are joined, the main thread can then exit the application.
Purely computation threads would probably be handled differently, right?
Is this efficient and safe? Is there a better way to do this?
Thanks!
In Windows, I use QueueUserAPC to call a function which throws an exception, causing threads to exit cleanly.
I wrote more about the details in this answer here:
How do I guarantee fast shutdown of my win32 app?
In summary, here's what happens:
Say thread A wants to terminate thread B (and then C, D, ...)
- Thread A calls
QueueUserAPC()
, passing the handle to thread B and the address of a function which will throw an Exception of class MyThreadExit. - Thread B runs normally until it calls something that checks for alertable waits. Maybe
WaitForSingleObjectEx
, maybeSleepEx
, or something else. - At this point, thread B runs the APC function passed earlier, causing the exception to be thrown in Thread B.
- All stack-allocated objects get automatically destructed correctly as the exception makes thread B 'unwind' its stack.
- The outermost thread function of thread B will catch the exception.
- Thread B now exits, possibly signalling to Thread A that it's done.
这篇关于从多线程应用程序有效退出(详细信息)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!