Advertisement
MikiSoft

Asynchronous Python explained (as simple as possible)

Oct 30th, 2019
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. # - Simple examples showing asynchronous workflow in Python -
  2.  
  3. #****** 1. asyncio approach (Python>=3.4) ******
  4. # Pros: It's the closest one to JavaScript's async/await, so it's expected to be fully optimized.
  5. # Cons: Limited Python version support, spanning from still recent one. I wouldn't recommend it anyways since LTS isn't yet reached for it, so beware - it can be buggy sometimes.
  6.  
  7. import asyncio
  8. @asyncio.coroutine
  9. def test_sleep(): # for Python>=3.5 can use "async def" without decorator above
  10.     print("before")
  11.     yield from asyncio.sleep(2) # for Python>=3.5 can use "await" instead
  12.     print("after")
  13.  
  14. @asyncio.coroutine
  15. def main():
  16.     task = asyncio.create_task(test_sleep())
  17.     yield from asyncio.sleep(1)
  18.     print(1)
  19.     yield from task
  20.  
  21. asyncio.get_event_loop().run_until_complete(main()) # for Python>=3.6 can use this instead: asyncio.run(main())
  22.  
  23. #****** 2. Threading approach ******
  24. # Pros: Long-term support, should work on all Python interpreters and versions in all environments.
  25. # Cons: It's overhead to do this for simple routines like below.
  26.  
  27. from threading import Thread
  28. from time import sleep
  29. def test_sleep():
  30.     print("before") # for Python 2 it's without parenthesis
  31.     sleep(2)
  32.     print("after")
  33.  
  34. thread = Thread(target=test_sleep)
  35. thread.start()
  36. sleep(1)
  37. print(1)
  38. thread.join()
  39. #EOF
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement