fork(2) download
  1. # io_bound/threaded.py
  2. import concurrent.futures as futures
  3. import requests
  4. import threading
  5. import time
  6. import asyncio
  7.  
  8. data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
  9.  
  10. async def async_task():
  11. for i in range(5):
  12. print(f"async running {i}")
  13. await asyncio.sleep(0.02)
  14. print("async done")
  15. return "I'm done"
  16.  
  17. def sleepy(n):
  18. time.sleep(1)
  19. return n*2
  20.  
  21. async def ExecuteSleep():
  22. loop = asyncio.get_running_loop()
  23. l = len(data)
  24. results = []
  25. # Submit needs explicit mapping of I/p and O/p
  26. # Output may not be in the same Order
  27. with futures.ThreadPoolExecutor(max_workers=l) as executor:
  28. result_futures = {d:loop.run_in_executor(executor, sleepy,d) for d in data}
  29. results = {d:await result_futures[d] for d in data}
  30.  
  31. return results
  32.  
  33. if __name__ == '__main__':
  34. print("Starting ...")
  35. t1 = time.time()
  36.  
  37. loop = asyncio.get_event_loop()
  38. tasks = [ExecuteSleep(),async_task()]
  39. # x,y = asyncio.run(asyncio.wait(tasks))
  40. x,y = loop.run_until_complete(asyncio.gather(*tasks))
  41.  
  42. print("Printing x {}".format(x))
  43. print("Printing y {}".format(y))
  44.  
  45. print("Finished ...")
  46. t2 = time.time()
  47. print(t2-t1)
Success #stdin #stdout 0.35s 30348KB
stdin
Standard input is empty
stdout
Starting ...
async running 0
async running 1
async running 2
async running 3
async running 4
async done
Printing x {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20, 11: 22, 12: 24, 13: 26, 14: 28, 15: 30, 16: 32, 17: 34, 18: 36, 19: 38, 20: 40}
Printing y I'm done
Finished ...
1.008409023284912