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

编程入门 行业动态 更新时间:2024-10-22 21:28:17
本文介绍了从另一个线程调用线程中的方法,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

本文发布于:2023-11-11 23:33:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579845.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   方法   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!