gpt4 book ai didi

python - 在类线程之间发送消息 Python

转载 作者:太空狗 更新时间:2023-10-29 21:16:09 26 4
gpt4 key购买 nike

有人知道如何在这段代码中不使用全局变量就可以将变量从 threadOne 发送(或获取变量)到 threadTwo 吗?如果没有,我将如何操作全局变量?只需在两个类之前定义它并在运行函数中使用全局定义?

import threading

print "Press Escape to Quit"

class threadOne(threading.Thread): #I don't understand this or the next line
def run(self):
setup()

def setup():
print 'hello world - this is threadOne'


class threadTwo(threading.Thread):
def run(self):
print 'ran'

threadOne().start()
threadTwo().start()

谢谢

最佳答案

您可以使用 queues以线程安全的方式在线程之间发送消息。

def worker():
while True:
item = q.get()
do_work(item)
q.task_done()

q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()

for item in source():
q.put(item)

q.join() # block until all tasks are done

关于python - 在类线程之间发送消息 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508906/

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