Skip to content

Instantly share code, notes, and snippets.

@kjelly
Created April 27, 2017 15:44
Show Gist options
  • Save kjelly/a5ae684c6859aad07cb8ab25be6b4c1b to your computer and use it in GitHub Desktop.
Save kjelly/a5ae684c6859aad07cb8ab25be6b4c1b to your computer and use it in GitHub Desktop.
useful async io sample code
import asyncio
from concurrent.futures import ThreadPoolExecutor
import random
import time
io_pool_exc = ThreadPoolExecutor()
async def openfile(name):
sleep_time = random.randint(1, 5)
with open(__file__, 'r') as f:
await asyncio.sleep(sleep_time)
content = await loop.run_in_executor(io_pool_exc, f.readlines)
print(name)
return sleep_time
async def test():
start = time.time()
future = asyncio.gather(
openfile('a.py'),
openfile('b.py'),
openfile('c.py'),
)
print('Jobs had scheduled')
await future
done = time.time()
elapsed = done - start
print("total sleep time: %d %s" % (sum(future.result()), future.result()))
print("elapsed time: %d" % elapsed)
print('jobs had done')
loop.stop()
loop = asyncio.get_event_loop()
asyncio.ensure_future(test())
loop.run_forever()
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment