如何保证我的win32应用程序的快速关闭? [英] How do I guarantee fast shutdown of my win32 app?

查看:97
本文介绍了如何保证我的win32应用程序的快速关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++ Win32应用程序,它有许多线程,当用户想关闭应用程序时可能正在做IO(HTTP调用等)。目前,我玩得很好,等待所有的线程结束,然后从 main 返回。有时,这需要比我想要的更长,实际上,让用户等待,我可以退出似乎毫无意义。但是,如果我只是继续从 main 返回,我很可能会崩溃,因为析构函数开始被调用,而仍有线程使用对象。

I've got a C++ Win32 application that has a number of threads that might be busy doing IO (HTTP calls, etc) when the user wants to shutdown the application. Currently, I play nicely and wait for all the threads to end before returning from main. Sometimes, this takes longer than I would like and indeed, it seems kind of pointless to make the user wait when I could just exit. However, if I just go ahead and return from main, I'm likely to get crashes as destructors start getting called while there are still threads using the objects.

因此,认识到在一个理想的,普遍的美德世界,最好的事情是等待所有线程退出,然后完全关闭,什么是下一个最好的真实世界解决方案?简单地使线程退出更快可能不是一个选项。目标是尽可能快地使过程死亡,以便例如可以在其上安装新版本。我做的唯一磁盘IO是在事务数据库,所以我不是非常担心拉这个插件。

So, recognizing that in an ideal, platonic world of virtue, the best thing to do would be to wait for all the threads to exit and then shutdown cleanly, what is the next best real world solution? Simply making the threads exit faster may not be an option. The goal is to get the process dead as quickly as possible so that, for example, a new version can be installed over it. The only disk IO I'm doing is in a transactional db, so I'm not terribly concerned about pulling the plug on that.

推荐答案

使用重叠IO,以便始终控制处理I / O的线程,并且可以随时停止线程;你可以让他们等待一个IOCP,并可以发布一个应用程序级别的关机代码,或者你可以等待你的OVERLAPPED结构中的事件,并等待你的所有线程请立即关闭事件。

Use overlapped IO so that you're always in control of the threads that are dealing with your I/O and can always stop them at any point; you either have them waiting on an IOCP and can post an application level shutdown code to it, OR you can wait on the event in your OVERLAPPED structure AND wait on your 'all threads please shutdown now' event as well.

总之,避免阻止您无法取消的电话。

In summary, avoid blocking calls that you can't cancel.

如果您不能,阻塞套接字调用做IO,那么你可以总是只关闭套接字,从线程已决定是时候关闭,并有正在做IO的线程总是检查'关闭现在'事件,然后重试...

If you can't and you're stuck in a blocking socket call doing IO then you could always just close the socket from the thread that has decided that it's time to shut down and have the thread that's doing IO always check the 'shutdown now' event before retrying...

这篇关于如何保证我的win32应用程序的快速关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆