event_loop_thread_base
event_loop_thread_base
event-loop is thread-based
import asyncio
import threading
def worker():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# loop.run_until_complete()
print("Worker thread loop:", id(asyncio.get_event_loop()))
threading.Thread(target=worker).start()
main_loop = asyncio.new_event_loop()
asyncio.set_event_loop(main_loop)
print("Main thread loop:", id(asyncio.get_event_loop()))
running-loop is event-loop that running
import asyncio
import threading
# Only apply to run Jupyter Notebook
import nest_asyncio
nest_asyncio.apply()
async def report():
# Now we're inside a running loop
print(f"Hey man, I'm running inside {threading.current_thread()}")
print(f"Running loop: {id(asyncio.get_running_loop())}. Current loop: {id(asyncio.get_event_loop())}")
def loop_run_to_complete(loop):
loop.create_task(report())
loop.run_until_complete(asyncio.sleep(1.0))
def worker():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop_run_to_complete(loop)
threading.Thread(target=worker).start()
main_loop = asyncio.new_event_loop()
asyncio.set_event_loop(main_loop)
# print("Main thread loop:", id(asyncio.get_event_loop()))
loop_run_to_complete(main_loop)
Hey man, I'm running inside <Thread(Thread-10 (worker), started 6305296384)>
Running loop: 4366786128. Current loop: 4366786128
Hey man, I'm running inside <_MainThread(MainThread, started 8697635008)>
Running loop: 4366783392. Current loop: 4366783392