Last active
July 14, 2022 06:26
-
-
Save liweicheng00/d8db15dff0c7d8ae2b0f3f93290a068b to your computer and use it in GitHub Desktop.
asyncio for block function
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 asyncio | |
import time | |
import random | |
def random_sleep(task_id: int): | |
for t in range(5): | |
sleep = random.randrange(1000, 2000, 1) | |
time.sleep(sleep / 1000) | |
print(f'task_id: {task_id}, running ({t})') | |
async def main(): | |
loop = asyncio.get_event_loop() | |
tasks = [] | |
for i in range(10): | |
tasks.append(loop.run_in_executor(None, random_sleep, int(i))) | |
for i in range(20): | |
print(f'Running.... ({i})') | |
time.sleep(0.5) | |
await asyncio.gather(*tasks) | |
if __name__ == "__main__": | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment