0

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

数据图

以下是一些相关的代码:

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")

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

提前致谢!

4

0 回答 0