Multiprocessing / threading confusion

Piet van Oostrum piet at vanoostrum.org
Fri Sep 6 00:28:05 EDT 2013


Piet van Oostrum <piet at vanoostrum.org> writes:


>     def run(self):
>         for n in range(5):
>             self.que.put('%s tick %d' % (self._pid, n))
>             # do some work
>             time.sleep(1)
>         self.que.put('%s has exited' % self._pid)

To prevent the 'exited' message to disappear if there is an exception in
the thread you should protect it with try -- finally:

    def run(self):
        try:
            for n in range(5):
                self.que.put('%s tick %d' % (self._pid, n))
                # do some work
                time.sleep(1)
        finally:
            self.que.put('%s has exited' % self._pid)

This doesn't help for the premature termination of the thread, as that
isn't an exception. But use the w.join() for that. Or you could put the
'exited' message after the w.join() command.
-- 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list