How could I ask Thread B to call B().Method() from inside Thread A's run?
Jeremy Jones
zanesdad at bellsouth.net
Wed Nov 30 08:09:19 EST 2005
could ildg wrote:
> I have 2 thead instances,
> A and B,
> In A's run method, if I call B.Method(), it will be executed in thead A,
> but I want B.Method() to be executed in B's thread.
> That's to say, I want to tell Thead B to do B's stuff in B's thread,
> kinda like PostMessage in win32.
> Can I do it in python?
> How?
> Thank you in advance.
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
More information about the Python-list
mailing list