获取线程在python中正确共享数据

时间:2014-06-27 19:14:02

标签: python

使用三个按钮创建一个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。初始运行将产生部分显示。如果我按下清除按钮清除显示屏,然后按开始按钮,我将收到一些数据和前一个显示交错显示的一些数据应该被删除。谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:2)

您希望使用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