python threading vs. thread

Top Page

Reply to this message
Author: Andy Sy
To: python
Old-Topics: Mig's Python threading example revisited
Subject: python threading vs. thread
Andy Sy wrote:
> I reworked Mig's threading example to use the non-OOP
> thread module approach instead of subclassing from
> Threaded. Also modified some loop structures for
> readability.
> ...snip...
> thread.start_new_thread(worker,(inQueue,outQueue,))
> # spawn worker function as a thread
> ...snip...
> time.sleep(1)
> # If we don't put this in, the worker thread will sometimes be
> # cut short if the main thread finishes before it does - meaning
> # the print q-size statement doesn't get to execute.
> # Ironically, a threading.Threaded object which has a join()
> # method to deal with situations like this did not seem to require
> # it
> ...snip...
> The OOP-style method used by Migs requires you to inherit a class
> from threading.Thread, override its __init__ function to accept
> the parameters the function normally would and then implement that
> function's innards in its run() method.
> Thus, you are invoking a method on a thread object (whose class you
> had to manually subclass from Threaded) instead of simply spawning a
> simple function to run as a separate thread.
> This approach may or may not be more suitable if you need to
> encapsulate your thread's functionality in an object. It seems,
> though, that for a lot of cases you do not need all this extra typing
> overhead. Use classes only when it's absolutely necessary as they
> can make for an unwieldy code structure - plain functions are leaner
> and meaner.

I have been happily using thread rather than threading all this time,
having not found the need for a join() until now and/or used workarounds.

There is, as it turns out, a way of starting a thread under the
threading module without resorting to the Rube Goldberg-ish OO way of
inheriting from Thread class. You simply do:

def worker(parm1,parm2):


By using threading instead of thread, you get the join(), isAlive(),
setDaemon() (whose naming is utterly misleading), getName() functions
which are all quite useful, and the idiom shown above is barely
more complicated - heck, it may even be simpler in some ways, than the
older start_new_thread() method.

Web and IT Consulting

Philippine Pythonista Hangout
python@??? (#Python @
Searchable Archives: