How could I ask Thread B to call B().Method() from inside Thread A's run?

How could I ask Thread B to call B().Method() from inside Thread A's run?

Post by Jeremy Jon » Thu, 01 Dec 2005 22:09:19



Here is a really simple, stupid example of what I think you're trying to
do. You probably want to use a Queue between your threads.

##########################
#!/usr/bin/python


import threading
import Queue


class A(threading.Thread):
def __init__(self, q):
self.q = q
threading.Thread.__init__(self)
def run(self):
for i in range(10):
print "Thread A putting \"something\" onto the queue"
self.q.put("something")
self.q.put("stop")

class B(threading.Thread):
def __init__(self, q):
self.q = q
self.proceed = True
threading.Thread.__init__(self)
def do_something(self):
print "Thread B doing something"
def do_stop(self):
print "Thread B should stop soon"
self.proceed = False
def run(self):
while self.proceed:
print "Thread B pulling sommething off of the queue"
item = q.get()
print "Thread B got %s" % item
getattr(self, "do_" + str(item))()

if __name__ == "__main__":
q = Queue.Queue()
a = A(q)
a.start()
b = B(q)
b.start()
a.join()
b.join()
##############################

HTH,

- jmj