Stop all threads using threading.Event()

為{幸葍}努か 提交于 2019-12-13 03:36:12

问题


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!

来源:https://stackoverflow.com/questions/55369844/stop-all-threads-using-threading-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!