Skip to content

Instantly share code, notes, and snippets.

@davidfarrugia
Created October 31, 2021 18:49
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 davidfarrugia/99d011ed7ae38283c7603e49e036dbf8 to your computer and use it in GitHub Desktop.
Save davidfarrugia/99d011ed7ae38283c7603e49e036dbf8 to your computer and use it in GitHub Desktop.
import concurrent.futures
import asyncio
import time
# we create our blocking target function for multi-threading
def blocking_func(n):
time.sleep(0.5)
return n ** 2
# we define our main coroutine
async def main(loop, executor):
print('creating executor tasks')
# create a list of coroutines and execute in the event loop
blocking_tasks = [loop.run_in_executor(executor, blocking_func, i) for i in range(6)]
print('waiting for tasks to complete')
# group the results of all completed coroutines
results = await asyncio.gather(*blocking_tasks)
print(f'results: {results}')
if __name__ == '__main__':
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main(loop, executor))
finally:
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment