2

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!

Tenserflu
  • 520
  • 5
  • 20
  • Please explain what `function_to_execute` does... – Dima Tisnek Mar 26 '19 at 07:35
  • Possible duplicate of [asyncio: Is it possible to cancel a future been run by an Executor?](https://stackoverflow.com/questions/26413613/asyncio-is-it-possible-to-cancel-a-future-been-run-by-an-executor) – Dima Tisnek Mar 26 '19 at 07:37
  • 1
    @DimaTisnek It computes a large amount then put it in a text file. – Tenserflu Mar 26 '19 at 07:39
  • best option: make `function_to_execute` asynchronous, don't use executors at all, periodically `await` something short so that the task can be cancelled. 2nd best option: wrap computation in subprocess, kill it if needed. – Dima Tisnek Mar 27 '19 at 05:46

1 Answers1

5

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.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • @DimaTisnek Please at least write a comment first before re-writing the answer. In this case the OP was asking about cancellation of a synchronous function, so cancellation of asyncio tasks doesn't help at all. (The OP probably shouldn't be using asyncio in that way in the first place, but that's a separate issue.) – user4815162342 Mar 28 '19 at 07:15