問題描述
我有一個 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 應用程序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!