Allows objects to be created and destroyed on a non-critical thread but passed over to a critical thread for use. Ideal for some audio applications. More...
#include <garbage_collected_object.h>
Allows objects to be created and destroyed on a non-critical thread but passed over to a critical thread for use. Ideal for some audio applications.
Because the system memory allocator probably uses a lock, it's at least theoretically possible to get a long delay when you create or delete an object. This could cause problems with real-time application, dropped data or glitches.
See Ross's page:
http://www.rossbencina.com/code/real-time-audio-programming-101-time-waits-for-nothing
Creating objects on the message thread avoids a possible memory allocation lock. They then need to be passed safely to the critical thread. After they are finished being used they should be deleted on the non-critical thread.
The GarbageCollector handles this last part.
You
The GarbageCollector will keep a reference to the object as well. And, when it detects that the total reference count has decreased to one, it'll delete the object safely on the message thread.
NOTE: It's important to (a) only create the objects on the message thread, and to (b) put them straight into a Reference Counting container. Otherwise the object may be deleted on the next timer call to GarbageCollector. (Why? The Timer which triggers the garbage collector is on the message thread. If you created the object on a different thread the Timer might fire whilst you are holding the object with a reference count of 0, and then it'll be deleted. Creating it on the message thread and putting it straight into a container means the ref-count is guaranteed to be incremented, preventing this embarrassing and fatal situation.).
IMPORTANT: If you are using this to share an object with another thread, DO NOT CHANGE the object after you've shared it. Think of it as immutable. Best to code it as: all methods to be const or thread-safe and lock-free.
It would be nice to get rid of constraint (a).
1.8.7