gpt4 book ai didi

python - 让线程在Python中正确共享数据

转载 作者:行者123 更新时间:2023-12-01 05:09:36 25 4
gpt4 key购买 nike

创建了一个带有三个按钮的 GUI,一个用于执行程序,一个用于停止程序,一个用于清除文本缓冲区。还有一个 TextView 来显示程序中的文本。以下是相关功能。

def clear_display(self, widget):
global textbuffer
start = textbuffer.get_start_iter()
end = textbuffer.get_end_iter()
textbuffer.delete(start, end)
self.print_display("")

def start_program(self):
global textbuffer
global mythread
global run
i = 0
while run:
msg = "Count = %s\n" % i
self.print_display(msg)
print ( "Count = %s\n" % i)
i += 1
mythread._Thread__stop()

def start_run(self, widget):
global run
global mythread
run = 1
mythread = Thread(target=self.start_program, args=())
mythread.start()

def stop_run(self, widget):
global run
global textbuffer
msg = "Halt Run\n"
self.print_display(msg)
run = 0

def print_display(self, msg):
global textbuffer
start = textbuffer.get_start_iter()
end = textbuffer.get_end_iter()
text = textbuffer.get_text(start, end)
text = text + msg
textbuffer.set_text(text)

我遇到的问题是获取要显示到 TextView 的数据。初始运行将产生部分显示。如果我按下清除显示屏的按钮,然后按下开始按钮,我将收到一些数据和一些来自先前显示交错的数据,这些数据应该被删除。谁能看到我做错了什么吗?

最佳答案

您需要使用 queue.Queue我将把你的实现留给你,但经典的用法是:

import threading, queue

q = queue.Queue()

def make_something(q, num_things_to_make):
for _ in num_things_to_make
new_thing = make_a_thing()
q.put(new_thing)

def use_something(q):
while True:
thing_to_use = q.get()
do_a_thing(thing_to_use)
q.task_done()

producer = threading.Thread(target=lambda: make_something(q, 8))
producer.start()

for _ in range(num_workers):
worker = threading.Thread(target=lambda: use_something(q))
worker.daemon = True
worker.start()

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

关于python - 让线程在Python中正确共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24459265/

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