Skip to content

Instantly share code, notes, and snippets.

@Odianosen25
Forked from lars-tiede/asyncio_loops.py
Created January 7, 2022 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Odianosen25/9724f53fd24db709ffddcc02ecb1c963 to your computer and use it in GitHub Desktop.
Save Odianosen25/9724f53fd24db709ffddcc02ecb1c963 to your computer and use it in GitHub Desktop.
asyncio + multithreading: one asyncio event loop per thread
import asyncio
import threading
import random
def thr(i):
# we need to create a new loop for the thread, and set it as the 'default'
# loop that will be returned by calls to asyncio.get_event_loop() from this
# thread.
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(do_stuff(i))
loop.close()
async def do_stuff(i):
await asyncio.sleep(random.uniform(0.1, 0.5)) # NOTE if we hadn't called
# asyncio.set_event_loop() earlier, we would have to pass an event
# loop to this function explicitly.
print(i)
def main():
num_threads = 10
threads = [ threading.Thread(target = thr, args=(i,)) for i in range(num_threads) ]
[ t.start() for t in threads ]
[ t.join() for t in threads ]
print("bye")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment