Multi thread for data processing and real-time display, thread and blocking in Python

The data that will be displayed to the user and the functions for processing them. Every time the user interacts with the data, the function must run on all data and the result is displayed to the user. This should work multi-threaded, so there is no user interaction lag when the function takes a long time to process.

Now I have 2 streams sharing List

, first running opengl loop at 60fps displaying content List

(not changing read-only). The second is sleeping, and when the user interacts with the data he wakes up, executes the function and writes the result to the List

assignment operation. The second thread interrupts the function and restarts if the user interacts before the function completes. Here's the implementation:

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

      

This works well, except that the fps of the first loop of the opengl thread is well 60, but when the user interacts, it drops to 20 when the time thread 2 is running. This is because the second thread is running from List

and thread 1 cannot read from it effective? There are no threads on it. I tried..

# done
self.output = result.copy()

      

.. so the function only works on a copy of the list, but with the same fps blob behavior. What's the best implementation of this (Queues perhaps)?

+3


source to share





All Articles