Calling a method in thread from another thread, python

雨燕双飞 提交于 2021-02-07 10:32:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!