从另一个线程python调用线程中的方法

时间:2018-07-11 11:42:47

标签: python python-3.x multithreading

如何实现线程之间的通信?

我有一个线程在其中处理一些事情,然后我需要从位于主程序线程中的对象中调用一个方法,并且该方法应在主进程中执行:

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 个答案:

答案 0 :(得分:2)

方法很多,一种是使用2个队列:

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)

输出:

Running help
Received  42
Running help
Received  42
Running help
Received  42
...etc
相关问题