PFT Essays: Real Time Safe Swap Containers

RealTimeSwapContainer is a class I wrote to contain PFT’s filters and modulators. The basic idea is to safely contain some dynamically allocated memory in a way that prevents a consumer from using it after it has been freed.

 

How it works:

 

The container has two members. One is an atomic<T *> to some allocated memory. The other is an atomic<int> that counts the number of uses of the contained object. When you want to use the object increment the use count. Then decrement the count when you’re done. This effectively protects it from being deallocated until you’re done using it. When you want to swap out a new object set the pointer in the container and then wait until you observe a use count of zero. This means nobody is currently using either object. The old one can be safely deallocated.

 

Naturally, there’s a little gray area in the middle where it’s impossible to know who’s accessing what and where they are. The important thing is that the edges of that area are very clear. The atomic use counter makes sure that when you enter and when you leave you know exactly what’s going on.

 

For some extra safety my implementation has a nested class called Borrow which ties its lifetime to the atomic use counter.

 

Github