简体   繁体   中英

How to stop loop running in executor?

I am running function that takes time to finish. The user has a choice to stop this function/event. Is there an easy way to stop the thread or loop?

class ThreadsGenerator:
    MAX_WORKERS = 5

    def __init__(self):
        self._executor = ThreadPoolExecutor(max_workers=self.MAX_WORKERS)
        self.loop = None
        self.future = None

    def execute_function(self, function_to_execute, *args):
        self.loop = asyncio.get_event_loop()
        self.future = self.loop.run_in_executor(self._executor, function_to_execute, *args)

        return self.future

I want to stop the function as quickly as possible when the user click the stop button, not waiting to finish its job.

Thanks in advance!

Is there an easy way to stop the thread or loop?

You cannot forcefully stop a thread. To implement the cancel functionality, your function will need to accept a should_stop argument, for example an instance of threading.Event , and occasionally check if it has been set.

If you really need a forceful stop, and if your function is runnable in a separate process through multiprocessing , you can run it in a separate process and kill the process when it is supposed to stop. See this answer for an elaboration of that approach in the context of asyncio.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM