gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:54:11 25 4
gpt4 key购买 nike

如何实现线程间的通信?

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com