从另一个线程调用线程中的方法,python [英] Calling a method in thread from another thread, python

查看:68
本文介绍了从另一个线程调用线程中的方法,python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现线程间的通信?

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

推荐答案

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

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)

输出:

Running help
Received  42
Running help
Received  42
Running help
Received  42
...etc

这篇关于从另一个线程调用线程中的方法,python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆