How do I know when a thread quits?

harold fellermann harold.fellermann at upf.edu
Tue Jun 7 16:44:43 CEST 2005


we had some off-group mails. A summary is posted to improve the 
knowledge
base of the list.

Prashanth wrote:

> Hi,
>
> I can use the threading module but I am just looking if there is a
> reliable way using the thread module.
>
> If I use a lock...
> Let us assume that the child thread has done a lck.release() but does
> not get a chance to quit before execution is whisked away from it and
> given to the main thread. Now the main thread sees that the lock has
> been released and quits. The child thread hasn't quit yet and we are
> back in the same problem.
>
> Don't you think?

Harold wrote:

I think it depends on when you release the child lock. if you do it 
after
refering to any data, e.g. as the last command in the child thread, you
should be on the save side, no?

- harold -

> Yes, I can assume that in most cases. However I don't think it happens
> so always. Even though infinitesimal, there is still a chance that it
> will not quit. I am looking for a mechanism using which I can make
> sure.

I don't understand what you mean. Why should the following code fail in 
any
case?


import thread

def parentThread() :
	lock = thread.allocate_lock()
	child = thread.start_new_thread(childThread,(parent,))
	lock.acquire()

def childThread(parent) :
	parent.lock.acquire()
	do_something_with_vars_from(parent)
	parent.lock.release()
	# don't do anything with parents vars after releasing the lock


I did not test it, but I cannot see any reason why this should fail.


> After the childThread executes parent.lock.release() execution may be
> taken away from it and given to the parent thread(note that the child
> thread hasn't quit yet). The parent thread which is waiting on the
> lock gets released and quits. Now the "still running" child thread
> tries to exit and based on my assumption attempts to call some cleanup
> func in some module which has been GC'ed due to the exit of the parent
> thread. This leads to an exception being thrown.


o.k. with this assumption, things might become a little more tricky.
one possibility: bind the modules you use to local variables in your 
child
thread. then they won't be GC'ed before childThread stops.
or (better): use Threading. it really isn't complicated to change your 
code
and timing issues become much simpler.

Referencing the module locally on the child thread does not seem like an
elegant solution besides I don't know which modules are involved in 
cleaning
up. Yes, I will use the Threading module but am just curious as to what 
can
be done to reliably use thread module.




More information about the Python-list mailing list