Guest User

Untitled

a guest
Jun 23rd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. import asyncio
  2. import signal
  3. from threading import Thread
  4. import time
  5.  
  6. from decorators import logger
  7.  
  8.  
  9. @logger
  10. async def do_some_work(x):
  11. await asyncio.sleep(x)
  12.  
  13.  
  14. @logger
  15. def more_work(x):
  16. time.sleep(x)
  17.  
  18.  
  19. @logger
  20. def block_the_main_thread():
  21. loop = asyncio.get_event_loop()
  22. loop.run_until_complete(do_some_work(5))
  23.  
  24. tasks = [asyncio.ensure_future(do_some_work(2)),
  25. asyncio.ensure_future(do_some_work(5))]
  26.  
  27. loop.run_until_complete(asyncio.gather(*tasks))
  28.  
  29.  
  30. def start_loop(loop):
  31. asyncio.set_event_loop(loop)
  32. loop.run_forever()
  33.  
  34.  
  35. @logger
  36. def on_a_new_thread():
  37. new_loop = asyncio.new_event_loop()
  38. t = Thread(target=start_loop, args=(new_loop,))
  39. t.start()
  40.  
  41. new_loop.call_soon_threadsafe(more_work, 20)
  42. asyncio.run_coroutine_threadsafe(do_some_work(5), new_loop)
  43. last_future = asyncio.run_coroutine_threadsafe(do_some_work(10), new_loop)
  44.  
  45. # Since we know which coroutine will finish last,
  46. # we can stop the loop when it's done
  47. last_future.add_done_callback(lambda f: new_loop.stop())
  48.  
  49.  
  50. if __name__ == '__main__':
  51. block_the_main_thread()
  52. on_a_new_thread()
Add Comment
Please, Sign In to add comment