Subj : Re: Freeing data structures in a threaded application To : comp.programming.threads From : David Schwartz Date : Wed Feb 16 2005 06:37 am "Luke Ehresman" wrote in message news:1108564185.484971.18870@f14g2000cwb.googlegroups.com... > I have a program with several threads. A session is created for a user > in one thread and stays around for 600 seconds and will then time out > with inactivity (assuming the user doesn't use the session in 600 > seconds). At that time, one of my threads will free up the session. Okay. > The potential problem I have noticed is that I have another thread that > does stuff to the session in the background. I was thinking this > morning, what happens if the session is freed up while the cache > manager thread is working on that same session? I do have a mutex to > lock the session, but that mutex is in the session data structure > itself, so once the structure is freed, the mutex goes away. Right, so you can't do things that way. You must never free a data structure while another thread is, or might be, using it. > The only way I can figure to get around this is to have a mutex outside > of the session data structure. But then how do I go about freeing up > that mutex after the session is invalid? It seems I would run into the > same problem. I can't keep around global mutexes because there may > potentially be thousands of users using this, logging in and out all > the time. (i.e. it needs to be scalable) There are many ways to do this. One way is to have a linked list (or other collection) of users that need to be removed. Have the cache manager thread free all the sessions in that linked list when it finishes its traverse. But the short and important issue is that cache manager thread *must* hold some sort of mutex on the list of all sessions or it cannot traverse that list. And you must hold that same mutex whenever you add a session to that list or remove a session from that list. Otherwise your code is already broken in more cases than just the one you mentioned. DS .