Archive for the ‘algorithms’ Category

h1

reference counter based memory management + bitching about life

June 8, 2009

The bitching about life part comes first.  I believe the DCFC song “No Sunlight” sums up my rant in that regard nicely, so I won’t waste the space here.  Okay I’m done with that.

Now, on to the not depressing stuff.  I was thinking of ways I could potentially speed up memory management with threads.  I was basically thinking along these lines:  I should queue my object deletions so that I can delete them on the side while the next iteration is in progress.  So I came up with an interesting system.  I haven’t implemented the threading yet, but I have seperated object deletion from the main loop entirely and it’s just tacked on the end for now.

Basically I implemented a reference counter object management system.  Each ManagedObject has a grab() and drop() method, used to count references.  When the number of references reaches zero, the drop() method calls the queue_deletion() method in the ObjectManager singleton.  The ObjectManager also keeps track of ManagedObject’s that are still kicking, so that they can be cleaned up at the very end if they weren’t properly dropped.  This should keep memory leaks from being as bad, though that doesn’t mean I won’t bust my ass trying to find all of them.  So the current code for updating is as follows:

void Engine::RunMainLoop(double timestep)
{
while (running)
{
if (!Update(timestep)) running = false;
if (!Render()) running = false;
ObjectManager::Singleton().CleanUp();
}
}

The ObjectManager deletes all things queued for deletion in CleanUp(). What I could do is simply start a cleanup thread that cleans up every second or so. For the threaded version it will lock the mutex for the queue to copy it over to a private queue and clear the public one so that it can be used again while the cleanup iterator goes through and deletes everything added previously. If you want the full classes, I shall have t3h c0dez in an article on custom memory management for C++ classes shortly.

EDIT: Okay, article’s up. It’s called “C++ custom memory management primer”. Link under My Articles in the sidebar.