问题
How can I achieve communication between threads?
I have one thread in which I do some stuff, then I need to call a method from an object that lives in the main program thread and this method should be executed in the main process:
class Foo():
def help(self):
pass
class MyThread(threading.Thread):
def __init__(self, connection, parser, queue=DEFAULT_QUEUE_NAME):
threading.Thread.__init__(self)
def run(self):
# do some work
# here I need to call method help() from Foo()
# but I need to call it in main process
bar = Foo()
my_work_thread = MyThread()
my_work_thread.run()
回答1:
There are many possibilities how to do it, one is using 2 queues:
from time import sleep
import threading, queue
class Foo():
def help(self):
print('Running help')
return 42
class MyThread(threading.Thread):
def __init__(self, q_main, q_worker):
self.queue_main = q_main
self.queue_worker = q_worker
threading.Thread.__init__(self)
def run(self):
while True:
sleep(1)
self.queue_main.put('run help')
item = self.queue_worker.get() # waits for item from main thread
print('Received ', item)
queue_to_main, queue_to_worker = queue.Queue(), queue.Queue( )
bar = Foo()
my_work_thread = MyThread(queue_to_main, queue_to_worker)
my_work_thread.start()
while True:
i = queue_to_main.get()
if i == "run help":
rv = Foo().help()
queue_to_worker.put(rv)
Output:
Running help
Received 42
Running help
Received 42
Running help
Received 42
...etc
来源:https://stackoverflow.com/questions/51284652/calling-a-method-in-thread-from-another-thread-python