Stop all threads using threading.Event()

2019-08-16 03:23发布

问题:

I am creating a multiple threads to execute a function that generates PDF. This process takes a lot of time, so the user has a choice to cancel the execution.

To stop a thread, I know that I can use threading.Event() to check if it will be set. However, the process of the function I am executing in my event loop is straight forward/linear (There is no loop to check regularly if the Event is set).

--threading class--

    def execute_function(self, function_to_execute, total_executions, execution_time, controller):
        self.event = threading.Event()
        self.event_list.append(self.event)
        self.loop = asyncio.get_event_loop()
        self.future = self.loop.run_in_executor(self._executor, function_to_execute, self.event, total_executions,
                                                execution_time, controller)


    def stop_executor(self):
        for event in self.event_list:
            event.set()
        self.event = None

        if self._executor:
            self._executor.shutdown(wait=False)
    def *function_to_execute*(self, event, total_execution, seconds=SECONDS_DEFAULT, controller=None):
        self.event = event
        self.controller = controller
        ...


My problem is that, I can't implement the Event to interrupt the threads without looping to regularly check the Event. Is there any other way around to stop all those threads? Or if I will still use the Event, is there any other logic to implement it?

Thanks in advance!