Stopping a thread from another one

Chris S. chrisks at NOSPAMudel.edu
Tue Jun 22 21:21:56 EDT 2004


Fabiano Sidler wrote:

> Hello Newsgroup!
> 
> In my Python script, I use the 'thread' module (not 'threading') and 
> 'signal' simultaneously. All spawned threads execute 
> 'pcapObject.loop(-1, callback)', which does not return.
> 
> The problem now is:
> When the script catch a signal (let's say: SIGHUP), only the main thread 
> is affected. But I need also the subthreads to be ended, because the 
> script reopen()s files on SIGHUP and would also re-create the threads.
> 
> NOT a solution is:
> The main thread sets a lock in the signal handler, the pcap-callback()
> function examines this lock everytime it's called, and if set, exit()s 
> the thread. This is not very beautiful.
> I would prefer, if I end the subthreads by the main thread.
> Is there any chance?
> 
> Greetings,
> fps

Incorporating a flag into each thread, which is checked periodically by 
the thread to decide whether or not it should end, is the safest way to 
terminate threads. However, if you're looking for a preemptive method 
that kills a thread unconditionally (whether the thread wants to die or 
not) then search this group for 'Kthread', a module created by Connelly 
Barnes, which implements a subclass of Thread incorporating this 
feature. Note that killing threads preemptively is unsafe and should 
only be done with care. This is why it's not part of Python's standard 
threading library.



More information about the Python-list mailing list