tags:

views:

273

answers:

3

So I have a container(any kind, probably std::map or std::vector) which contains objects of a class with some network thing running in a thread that checks if it is still connected (the thread is defined inside that class and launches when constructed).

Is there any way I can make the object delete itself from the container when its disconnected or should I move the thread outside the object and use that class just to store data?

+5  A: 

In order for the object to delete itself from the container, it will have to know which container it is in. You will need to maintain a pointer to the container in the object. You will also have to protect the container with a lock to stop multiple threads accessing the container at the same time.

I think I prefer your second solution - some managing object looks after removing dead objects from the collection. If nothing else, this will be quite a bit easier to debug and the locking logic becomes centralised in a single object.

anon
+1  A: 

STL containers tend to assume they're storing values; objects that can be copied and where copies are identical. Typically, objects which have threads fit poorly into that model. They have a much stronger sense of identity. In this case, you definitely have indentity - a copy of the object in a container is distinct from a copy outside.

MSalters
"Tend to assume"?The assume or they don't assume that the objects stored are values: they aren't human beings!
akappa
STL containers ONLY store values. Those values may, of course, be pointers.
anon
+1  A: 

I would have am unload queue.

When a thread notices that the connection is down it registers the object (and continer) with the unload queue tides everything up as much as possible then the thred terminates.

A separate thread is then inside the unload queue. Its sole purpose is to monitor the queue. When it sees a new object on the queue, remove it from the container and then destroy it (syncing with the objects thread as required).

Martin York
I don't really understand what an unload queue means but I used something similar;
csiz
A job queue (I use the term unload as you are unloading the object from a container). You just place a job on a queue (In this case the job is to unload/delete an objet from a container). A separate thread then processes the jobs one at a time.
Martin York