Out-of-Memory recovery

Jason House jason.james.house at gmail.com
Sun Jan 4 16:44:41 PST 2009


bearophile wrote:

> I have seen this:
> http://dobbscodetalk.com/index.php?option=com_content&task=view&id=966
> 
> Walter (from a comment written by someone else):
> 
>>A critical program, such as life support machines, flight control 
>>systems, etc., cannot be allowed to fail.<
> 
> Such software most probably works with a fixed amount of memory (or at
> compile time it's known the maximum amount of memory required), so that's
> not an example where recovering from out-of-bound errors is important.

That's a good point :)


>>The memory manager can have user supplied callbacks to release memory in
>>such cases.<
> 
> This is interesting. What's a possible API/semantics for such thing?

Based on what I see in the docs for core.memory, I'd envision something like the following:

// Sample allocation logic
void* allocate(int nBytes){
  void* result = null;
  if (tryAllocate(nBytes, &result))
    return result;
  onSoftOutOfMemory();
  if (tryAllocate(nBytes, &result))
    return result;
  onHardOutOfMemory();
}

// Default handlers for out of memory
void onSoftOutOfMemory(){
  foreach(callback; registeredOutOfMemoryHandlers)
    callback();
  GC.collect();
}
void onHardOutOfMemory(){
  abort(-1);
}

// Exposed functions to use this new functionality
void addOutOfMemoryHandler(void function () callback);
void addOutOfMemoryHandler(void delegate () callback);
void removeOutOfMemoryHandler(void function () callback);
void removeOutOfMemoryHandler(void delegate () callback);  


Theoretically, onHardOutOfMemory could be replaced with a version that throws for those who believe they can't live without it.



> 
> Bye,
> bearophile




More information about the Digitalmars-d mailing list