Tenserflu
Tenserflu

Reputation: 583

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!

Upvotes: 2

Views: 2341

Answers (1)

user4815162342
user4815162342

Reputation: 154886

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.

Upvotes: 5

Related Questions