In a networking project I have multiple objects that each have a message queue (linked list). Each object also has a few clients, and each client has a pointer to a node in the queue. When a client receives the message its pointer points to, its pointer goes to the next message in the queue. Now, when all the clients have received a message, I want that message to be freed so it doesn’t take up memory. I did this by having a separate thread go through the objects and delete the unneeded messages, acting as a GC, but is there a better way of doing it?
Thanks.
You might be able to use reference counting to handle this. Assuming that all of the pointers to the queue elements are from the outside in (and never between queue elements), you can store in the queue cell a count of the number of pointers to it. Whenever you add a new pointer, you increment this reference count, and whenever a part of the program is done using the cell it drops the reference count, freeing it when it reaches zero. That way, as long as there’s an outstanding pointer to the cell, it won’t be freed, and as soon as the last reference to the queue cell is broken it will be reclaimed. You don’t need a separate thread to do this.