-
Notifications
You must be signed in to change notification settings - Fork 0
asyncio
Jasper Zanjani edited this page Sep 14, 2020
·
1 revision
👉 Demistifying Python's Async and Await keywords
The asyncio module offers an implementation of coroutines which allow tasks to control context switching to implement concurrency.
The await keyword is a checkpoint that indicates where it is safe for the process to go to another coroutine, allowing total control over context switching
import asyncio
import time
counter = 0
async def func1():
global counter
while True:
counter += 1
counter -= 1
await asyncio.sleep(0)
async def func2():
global counter
while True:
counter += 1
counter -= 1
await asyncio.sleep(0)
asyncio.gather(func1(), func2())
asyncio.get_event_loop().run_forever()async def get_users():
users = await client.do_query('select * from users')
return users
async def main():
task = asyncio.create_task(get_users())
# ...
await task
asyncio.run(main())Allows the joining of multiple threads.
async def get_users():
users = await client.do_query('select * from users')
return users
async def main():
await asyncio.gather(
get_users(),
get_users(),
)
asyncio.run(main())async def get_users():
users = await client.do_query('select * from users')
return users
asyncio.run(get_users())async def main():
users = await get_users()
print(users)
asyncio.run(main())- argparse ?
- array ?
- asyncio ?
- bisect ?
- csv ?
- ctypes ?
- curses ?
- datetime ?
- functools ?
- getpass ?
- glob ?
- heapq ?
- http ?
- json ?
- logging ?
- optparse ?
- os ?
- pathlib ?
- platform ?
- pythonnet ?
- random ?
- socket ?
- subprocess ?
- sqlite3 ?
- sys ?
- termcolor ?
- threading ?
- trace ?
- typing ?
- unittest ?
- urllib ?
- venv ?
- weakref ?
- winrm ?