[Tutor] Tread or threading
Kent Johnson
kent37 at tds.net
Sat Feb 16 16:50:32 CET 2008
Michael Bernhard Arp Sørensen wrote:
> Hi there.
>
> I've been reading in books and homepages about threads. Apparently,
> "threading" is better than "thread", right?
>
> I've been trying to write a simple proof of concept code using
> "treading" inside a class. It was easely done with "thread", but it was
> a lot harder with "threading". I want to be able to write a program like
> this:
>
> class myapp():
> def __init__(self):
> self.queue = queue.Queue()
> self.lock = threading.Lock()
Queue.Queue is already threadsafe, you don't have to add a lock around
it. Queue.get() and Queue.put() already have the semantics you are
trying to achieve with the lock.
> def main(self):
> start_inputthread()
> start_outputthread()
> wait_for_both_threads_to_end()
t1 = Thread(target=self.inputthread)
# Note no parentheses after inputthread
t1.start()
t2 = Thread(target=self.outputthread)
t2.start()
t1.join()
t2.join()
> All the examples I've seen was done by creating a class as a subclass of
> threading.Thread. Isn't there a way to make individual methods a thread
> like we do with the simpler "thread" module, but by using threading?
Use the target parameter to Thread() to pass an individual method or
function. Here is an example:
http://redclay.altervista.org/wiki/doku.php?id=projects:python-threading#example_4empy_full_queue
Kent
More information about the Tutor
mailing list