Entry
How can I get one thread (messenger) to send a message to another thread (waiter) as a responce to some action?
May 13th, 2000 06:08
unknown unknown, Fredrik Lundh, Glyph Lefkowitz
Solution 1:
The trick is to use a thread-safe queue to pass information from
the messenger to the worker thread. Here's an example, adapted
from a queue example in the eff-bot guide:
# adapted from queue-example-1.py
import threading
import Queue
import time, random
class Worker(threading.Thread):
def __init__(self, queue=None):
if queue is None:
queue = Queue.Queue(0) # no limit
self.__queue = queue
threading.Thread.__init__(self)
def add(self, item):
self.__queue.put(item)
def shutdown(self):
self.__queue.put(None)
def run(self):
while 1:
item = self.__queue.get()
if item is None:
break # reached end of queue
# pretend we're doing something that takes 10-100 ms
time.sleep(random.randint(10, 100) / 1000.0)
print "task", item, "finished"
>>> worker = Worker()
>>> worker.start()
>>> worker.add(1)
>>> task 1 finished
worker.add(2); worker.add(3)
>>> task 2 finished
task 3 finished
>>> worker.shutdown()
</F>
<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
Solution 2:
###
Python 1.5.2 (#0, Apr 3 2000, 14:46:48) [GCC 2.95.2 20000313 (Debian
GNU/Linux)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> from threading import *
>>> from Queue import *
>>> q=Queue(100)
>>> def Waiter():
... while 1:
... x=q.get()
... print 'Waiter got a message ->',x
...
>>> def Messenger():
... while 1:
... x=raw_input("Messenger: ")
... q.put(x)
...
>>> w=Thread(target=Waiter)
>>> w.start()
>>> Messenger()
Messenger: hi de ho
Messenger: Waiter got a message -> hi de ho
###
The way that second line of output appears is a bit of foreshadowing
of the nasty tricky things that await you down the path of
multi-threading.