Python中多线程处理数据和实时显示、线程和锁设计

2024-03-28 19:36:23 发布

您现在位置:Python中文网/ 问答频道 /正文

有数据要显示给用户和功能来处理它们。每次用户与数据交互时,必须对所有数据运行函数,并将结果显示给用户。这应该是多线程的,这样当函数需要较长时间处理时就不会出现用户交互延迟。在

现在,我有两个线程共享List,第一个线程是以60fps的速度运行opengl循环,显示List的内容(而不仅仅是读取)。第二个是休眠,当用户与数据交互时,它会被唤醒,运行函数并通过赋值操作将结果写入List。如果用户在函数完成之前进行交互,第二个线程将中断函数并重新启动。实现如下:

class RestartableThread(threading.Thread):
    def __init__(self, input, output_list):
        threading.Thread.__init__(self)
        self.output = output_list
        self.input = input
        self._restart = threading.Event()
        self._paused = threading.Event()
        self._state = threading.Condition()

    def restart(self, input):
        with self._state:
            self.input = input    # get new input
            self._restart.set()
            self._paused.clear()
            self._state.notify()  # unblock self if in paused mode

    def run(self):
        while True:
            with self._state:
                if self._paused.is_set():
                    self._state.wait() # wait until notify() - the thread is paused

            self._restart.clear()
            self.function()

    def function(self):
        # start empty
        result = []
        for elem in self.input:
            # end if restarted
            if self._restart.is_set():
                return
            # do something with elem that takes time
            result.append(elem)
        # done
        self.output = result
        # enter sleep
        with self._state:
             self._paused.set()  # enter sleep mode
        return

除了第一个线程的opengl循环的fps很好地达到了60,但是当用户交互时,线程2的工作时间降到了20。是因为第二个线程与List一起工作,而线程1不能有效地从中读取数据吗?上面没有锁。我试过了。。在

^{pr2}$

…所以该函数只对列表的副本有效,但fps-drop行为相同。最好的实现方式是什么(可能是队列)?在


Tags: 数据函数用户selfinputoutputdefwith