Skip to content

Instantly share code, notes, and snippets.

@liweicheng00
Last active July 14, 2022 06:26
Show Gist options
  • Save liweicheng00/d8db15dff0c7d8ae2b0f3f93290a068b to your computer and use it in GitHub Desktop.
Save liweicheng00/d8db15dff0c7d8ae2b0f3f93290a068b to your computer and use it in GitHub Desktop.
asyncio for block function
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