Subj : Re: Freeing data structures in a threaded application To : comp.programming.threads From : David Schwartz Date : Wed Feb 16 2005 06:56 am "Luke Ehresman" wrote in message news:1108564948.066645.184270@o13g2000cwo.googlegroups.com... > Thanks for the tips. I do have a mutex for the session list for adding > and removing sessions from that list. However, I also have separate > mutexes for operating on individual sessions. That way I can do > operations on multiple sessions at the same time (but can only modify > the session list one at a time). That's good. > Your idea of keeping a list of sessions that are pending deletion is a > great idea. That's the piece I was missing. Are you sure you need one? Why not just acquire the lock that protects the list of sessions and delete the session? Just make sure any code that needs the lock on the list of sessions releases any locks on individual sessions first. So the code looks like this: mySession->Lock(); // lock this session if(mySession->NeedToDelete()) { // we need to delete it mySession->Unlock(); SessionTable->Lock(); // trade for the session table lock, our session might not exist anymore if(SessionTable()->FindSession(mySession)) { // our session still exists SessionTable()->Remove(mySession); // remove this session SessionTable->Unlock(); // since we removed the session from the table, nobody else did // therefore, nobody else could have deleted it, so it must still exist mySession()->Lock(); // at this point, we hold the lock on the session and it is not in the session list // no other thread could possibly reference this session if(mySession()->NeedToDelete()) { mySession()->Unlock(); delete mySession(); } else { // wow, there must have been some activity mySession()->Unlock(); } } else { // wow, the cache manager must have deleted it right before we could SessionTable()->Unlock(); } } else mySession.Unlock(); Not pretty, but variations on this may work very well for your particular situation. DS .