-
-
Save davidfarrugia/99d011ed7ae38283c7603e49e036dbf8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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