Overriding Thread.join in derived class.

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Aug 19 15:40:25 EDT 2007


On 18 ago, 04:31, Graham Dumpleton <Graham.Dumple... at gmail.com> wrote:

> If one creates a thread using threading.Thread and makes it a daemon
> by calling setDaemon(), then when Python is exiting it will not
> attempt to call join() on that thread and wait for it to complete
> first. [...]
> End result is that it could result in a Python exception at some
> point, evidenced by messages starting with:
> Exception in thread Thread-1 (most likely raised during interpreter
> shutdown) [...]
>
> In order to avoid this, do people think that as an alternative to
> creating daemonised thread that it would be reasonable to create a
> derived Thread class for the particular task which overrides
> Thread.join() method to set some flag or otherwise take some action
> that the thread would notice to tell it to stop, and then call base
> class Thread.join().
>
> This way you can flag the thread to shutdown automatically when Python
> is going around calling join() on non daemonised threads.
>
> Or am I missing the obvious as far as ways of flagging threads to tell
> them to stop?
>
> Note that this is where Python is being used embedded in a C program.
> There is no Python main function where code can be put to signal
> threads to otherwise stop.

This last statement is important. You need "some" way to tell the
threads to stop working. Usually the thread's run() method is a big
loop; you need to tell it somehow to exit the loop. By example, if you
are using a Queue, put a sentinel object in it; or use an Event
object; or at least a global variable.
Overriding thread.join() as you suggest above may be a good place to
do that, if you don't have another chance.

--
Gabriel Genellina




More information about the Python-list mailing list