高效退出多线程应用程序(具体)
我已经阅读了一些有关将消息从线程冒泡到所有其他线程以优雅退出的正确方法的资料(每个线程执行其自己的退出例程)。其中,我喜欢全局原子布尔值的想法,它可以从任何线程进行标记,并且所有其他线程检查此标记以执行退出例程 - 当所有线程都加入时,主线程可以退出应用程序。
纯粹的计算线程可能会有不同的处理方式,对吧?
这样高效、安全吗?有更好的方法吗?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不喜欢线程检查布尔(或其他)状态变量来知道何时做什么,因为这是浪费。线程必须旋转,不断检查变量以查看是否有新指令。这会烧毁CPU。
更好的选择是创建一个信号量或在 Windows 中创建一个事件,并让所有线程等待该信号量。线程可以在不忙时休眠,并且不会仅仅为了检查变量而从其他执行实际工作的线程窃取时间片。
I'm not a fan of threads checking boolean (or other) status variables to know when to do what, because it's wasteful. The threads would have to spin, constantly checking the variable to see if there are new instructions. This burns the CPU.
A better option is to create a semaphore or in Windows an event, and have all the threads wait on that. The threads can sleep while they aren't busy, and won't steal time slices from other threads doing real work simply to check a variable.
在 Windows 中,我使用 QueueUserAPC 调用一个引发异常的函数,导致线程干净退出。
我在此答案中写了更多有关详细信息的信息:
如何保证快速关闭我的 win32 应用程序?
总之,会发生以下情况:
假设线程 A 想要终止线程 B(然后是 C、D,...)
QueueUserAPC()
,将句柄传递给线程 B 以及将抛出 MyThreadExit 类异常的函数的地址。WaitForSingleObjectEx
,也许是SleepEx
,或者其他什么。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, ...)
QueueUserAPC()
, passing the handle to thread B and the address of a function which will throw an Exception of class MyThreadExit.WaitForSingleObjectEx
, maybeSleepEx
, or something else.