线程结果与非线程结果(python)没有给出相同的结果

时间:2013-10-20 23:28:21

标签: multithreading python-3.x

我已经创建了一个程序来生成我稍后绘制的函数数据点。该程序采用一个定义函数的类,创建一个数据输出对象,当被调用时,该对象生成数据到文本文件。为了使整个过程更快,我将作业放在线程中,但是当我这样做时,生成的数据并不总是正确的。我附上了一张照片来说明我的意思:

Data Plot

以下是一些相关的代码:

from queue import Queue
import threading
import time

queueLock = threading.Lock()
workQueue = Queue(10) 

def process_data(threadName, q, queue_window, done):
    while not done.get():
        queueLock.acquire()         # check whether or not the queue is locked
        if not workQueue.empty():
            data = q.get()
            # data is the Plot object to be run
            queueLock.release()
            data.parent_window = queue_window
            data.process()
        else:
            queueLock.release()
        time.sleep(1)

class WorkThread(threading.Thread):
    def __init__(self, threadID, q, done):
        threading.Thread.__init__(self)
        self.ID = threadID
        self.q = q
        self.done = done
    def get_qw(self, queue_window):
        # gets the queue_window object
        self.queue_window = queue_window
    def run(self):
        # this is called when thread.start() is called
        print("Thread {0} started.".format(self.ID))
        process_data(self.ID, self.q, self.queue_window, self.done)
        print("Thread {0} finished.".format(self.ID))

class Application(Frame):
    def __init__(self, etc):
        self.threads = []
        # does some things
    def makeThreads(self):
        for i in range(1, int(self.threadNum.get()) +1):
            thread = WorkThread(i, workQueue, self.calcsDone)
            self.threads.append(thread)
    # more code which just processes the function etc, sorts out the gui stuff.

在一个单独的类中(因为我正在使用tkinter,因此用于获取运行线程的实际代码在另一个窗口中调用)(self.parent是Application类):

    def run_jobs(self):
        if self.running == False:
            # threads are only initiated when jobs are to be run
            self.running = True
            self.parent.calcsDone.set(False)
            self.parent.threads = []        # just to make sure that it is initially empty, we want new threads each time
            self.parent.makeThreads()
            self.threads = self.parent.threads

            for thread in self.threads:
                thread.get_qw(self)
                thread.start()

            # put the jobs in the workQueue
            queueLock.acquire()
            for job in self.job_queue:
                workQueue.put(job)
            queueLock.release()
        else:
            messagebox.showerror("Error", "Jobs already running")

这是与线程相关的所有代码。 我不知道为什么当我用多个线程运行程序时,一些数据点是不正确的,而只用一个单线程运行它,数据就完美了。我试着查找“线程安全”进程,但找不到任何东西。

提前致谢!

0 个答案:

没有答案