Suggestion: Critical Section for ReferenceCountedObject


In my sequencer, Clips are referenced by lots of classes, either in the audio callback or GUI thread. It would be nice to add some user-definable Critical Section around the code where the reference count gets decremented (but excluding the part where the object gets deleted), so the audio callback could never encounter an invalid reference counted Clip. So in my case I’d just pass a pointer to the CriticalSection that is used in the audio callback to the ReferenceCountedObject (or ReferenceCountedObjectPointer?).


I don’t understand why you’d ever need that… By default the ReferenceCountedObject class uses atomic values, and is thread-safe (??)


Ok, one of the problems I see though is that if the last reference is held by the audio callback, the deletion will occur in the audio callback, and this could take very long depending on the object and lead to audio drops. So I think my suggestion is still valid for that case, or not?


But if your audio thread holds the only reference, then how could any other thread possibly take over the job of deleting it?? By definition, nothing else would have a reference to the object!

You can solve the problem in many other ways without changing the reference-counting class. E.g. you could make your audio thread pass any objects it wants to get rid of to some kind of object which would release them later on in a different thread.

But also bear in mind that ReferenceCountedObjectPtr is templated, and can work with any class that implements the appropriate methods. You don’t need to use ReferenceCountedObject as your base, you could write your own decReferenceCount() and do any kind of crazy custom reference counting system that you want to.


Ah ok I see. I’ll just make my own ReferenceCountedObject in that case, seems to be the best solution! Thanks!


Don’t use a critical section though - stick to atomic counters if you’re using them in an audio thread.