在Windows上检测内存不足之前的分配在Windows上开始失败 [英] Detecting memory running low BEFORE allocations start failing on Windows

查看:98
本文介绍了在Windows上检测内存不足之前的分配在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.

在对"new"的调用实际失败之前,检测进程内存不足的最佳方法是什么?我们可以调用GetProcessWorkingSetSize()GetProcessMemoryInfo()之类的API函数,但是您如何知道何时达到给定计算机的限制(例如,最大分配的80%)?

What's the best way to detect that memory for a process is running low before calls to 'new' actually fail? We could call API functions like GetProcessWorkingSetSize() or GetProcessMemoryInfo() but how do you know when the limits on a given machine are being reached (e.g. with 80% of maximum allocations)?

推荐答案

  • 在启动时,分配内存预留.
  • 然后使用set_new_handler()安装一个钩子,该钩子将检测分配失败.
  • 发生以下情况:
    • 释放预留空间(以便您有足够的可用内存来使用).
    • 运行您的代码以查找并释放低优先级的对象.
    • 工作完成后,请尝试重新分配储备金(下一次).
    • 最后返回以让原始分配尝试重试.
      • At start up, allocate a memory reserve.
      • Then use set_new_handler() to install a hook that will detect allocations failures.
      • 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.
        • 这篇关于在Windows上检测内存不足之前的分配在Windows上开始失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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