Reputation: 583
I have event loop that runs the function asynchronously. However, that function generates big data so the execution will be a little bit long when the program visits that function. I also implemented a stop button, so the app will exit that function even if the event loop is not yet finish. The problem is that is how to exit on that function immediately or how to kill a thread in asyncio.
I already tried using a flag in the function but the execution of the function is fast enough to check the flag before the user click on the stop button. To be short, the thread already running on the background.
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
def stop_function(self):
if self._executor:
self._executor.shutdown(wait=False)
self.loop.stop()
self.loop.close()
Is there something wrong or missing on the code I've given? The expected output should be, the program will not generate the data at the end if I click the stop button.
Upvotes: 1
Views: 1410
Reputation: 1437
You can use threading.Event passing it to your blocking function
event = threading.Event()
future = loop.run_in_executor(executor, blocking, event)
# When done
event.set()
The blocking function just has to check is_set and when you want to stop it just call event.set() as above.
def blocking(event):
while 1:
time.sleep(1)
if event.is_set():
break
Upvotes: 2