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

标签 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()

最佳答案

有很多可能性如何做到这一点,一种是使用 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

关于python - 从另一个线程调用线程中的方法,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51284652/

相关文章:

由 C++ Python 3 绑定(bind)

python - 我需要根据形状将原始图像分成子部分

python - PyTorch - 将张量与标量相乘得到零向量

python-3.x - 如何在文本文件的第二行上写而忽略第一行?

java - Java 中的原子性和内存顺序

python - logrotate 后日志开头的空值

python-3.x - 如何在python中使用spotify的annoy库?

python - 什么更快 : Python 3's ' len' or numpys shape?

multithreading - Delphi 2007 AsyncMultiSync 不起作用

multithreading - 生产者-消费者使用赋值