简体   繁体   English

检测内存不足之前在Windows上分配开始失败

[英]Detecting memory running low BEFORE allocations start failing on Windows

We have an application that could potentially allocate a large number of small objects (depending on user input). 我们有一个可能会分配大量小对象的应用程序(取决于用户输入)。 Sometimes the application runs out of memory and effectively crashes. 有时,应用程序会耗尽内存并导致崩溃。

However, if we knew that memory allocations were becoming tight there are some lower-priority objects which could be destroyed and thereby allow us to gracefully degrade the user results. 但是,如果我们知道内存分配变得紧张,那么可以销毁一些优先级较低的对象,从而使我们能够优雅地降低用户结果。

What's the best way to detect that memory for a process is running low before calls to 'new' actually fail? 在调用“new”实际上失败之前,检测进程内存的最佳方法是什么? We could call API functions like GetProcessWorkingSetSize() or GetProcessMemoryInfo() but how do you know when the limits on a given machine are being reached (eg with 80% of maximum allocations)? 我们可以调用像GetProcessWorkingSetSize()GetProcessMemoryInfo()这样的API函数,但是你怎么知道什么时候达到给定机器的限制(例如80%的最大分配)?

  • At start up, allocate a memory reserve. 在启动时,分配内存预留。
  • Then use set_new_handler() to install a hook that will detect allocations failures. 然后使用set_new_handler()来安装将检测分配失败的钩子。
  • When one happens: 当一个发生时:
    • Free the reserve (so you have enough free memory to work with). 释放储备(这样你就有足够的可用内存)。
    • Run your code that finds and frees low priority objects. 运行查找和释放低优先级对象的代码。
    • When that has done its job, try to reallocate the reserve again (for next time). 当它完成其工作时,尝试再次重新分配保留(下次)。
    • Finally return to let the original allocation attempt retry. 最后返回让原始分配尝试重试。

If it's a 32-bit process then you would want to ensure that you don't use more than 1.6GB, which is 80% of 2.0GB, the max allowed for your process. 如果它是一个32位进程,那么您需要确保不要使用超过1.6GB,这是2.0GB的80%,这是您的进程允许的最大值。 Calling GlobalMemoryStatusEx will fill in the struct MEMORYSTATUSEX.ullAvailVirtual , when this is only 400MB available (or less) then you are at your threshold. 调用GlobalMemoryStatusEx将填充结构MEMORYSTATUSEX.ullAvailVirtual ,当这个只有400MB可用(或更少)时,你就达到了你的门槛。

Check this answer Win32/MFC: How to find free memory (RAM) available? 检查此答案Win32 / MFC:如何找到可用的空闲内存(RAM)? .

You need to periodically find available free memory and stop allocating at some limit. 您需要定期查找可用的可用内存并在某个限制内停止分配。 As explained in above referred answer, you can use GlobalMemoryStatusEx , and/or VirtualQueryEx . 如上面提到的答案中所述,您可以使用GlobalMemoryStatusEx和/或VirtualQueryEx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM