I am having a very basic function that takes in a string called name and a callback function. My objective is to be able to terminate from the function, by raising a Keyboard interrupt gracefully.
On the main thread, I am watching for Keyboard interrupt, while foo
is running on the background thread.
However at thread.join()
, I am running into a threading error.
import threading
import asyncio
import sys
import time
def callback_handler(name):
print(f"Hi im a callback_handler, my name is {name}")
async def foo(name, cb):
await asyncio.sleep(5)
print("Inside foo")
if cb:
await asyncio.sleep(5)
cb(name)
event_loop = asyncio.new_event_loop()
task = event_loop.create_task(foo("bar", callback_handler))
thread = threading.Thread(target=event_loop.run_forever, daemon=True)
thread.start()
try:
while True:
message = input("> ")
except (KeyboardInterrupt, EOFError):
print('Received KeyboardInterrupt')
thread.join()
Error:
python3 cb.py
> ^CReceived KeyboardInterrupt
^CTraceback (most recent call last):
File "/Users/lamathe/Desktop/cb.py", line 34, in <module>
thread.join()
File "/usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 1060, in join
self._wait_for_tstate_lock()
File "/usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 1080, in _wait_for_tstate_lock
if lock.acquire(block, timeout):
KeyboardInterrupt
Would highly appreciate any support on this.