PEP 0492 - Python 3.5 async keyword -
pep 0492 adds async
keyword python 3.5.
how python benefit use of operator? example given coroutine
async def read_data(db): data = await db.fetch('select ...')
according docs achieves
suspend[ing] execution of read_data coroutine until db.fetch awaitable completes , returns result data.
does async
keyword involve creation of new threads or perhaps use of existing reserved async thread?
in event async
use reserved thread, single shared thread each in own?
no, co-routines not involve kind of threads. co-routines allow cooperative multi-tasking in each co-routine yields control voluntarily. threads on other hand switch between units @ arbitrary points.
up python 3.4, possible write co-routines using generators; using yield
or yield from
expressions in function body create generator object instead, code executed when iterate on generator. additional event loop libraries (such asyncio
) write co-routines signal event loop going busy (waiting i/o perhaps) , co-routine run in meantime:
import asyncio import datetime @asyncio.coroutine def display_date(loop): end_time = loop.time() + 5.0 while true: print(datetime.datetime.now()) if (loop.time() + 1.0) >= end_time: break yield asyncio.sleep(1)
every time above code advances yield asyncio.sleep(1)
line, event loop free run different co-routine, because routine not going next second anyway.
because generators can used sorts of tasks, not co-routines, , because writing co-routine using generator syntax can confusing new-comers, pep introduces new syntax makes clearer writing co-routine.
with pep implemented, above sample written instead as:
async def display_date(loop): end_time = loop.time() + 5.0 while true: print(datetime.datetime.now()) if (loop.time() + 1.0) >= end_time: break await asyncio.sleep(1)
the resulting coroutine
object still needs event loop drive co-routines; event loop await
on each co-routine in turn, execute co-routines not await
ing complete.
the advantages native support, can introduce additional syntax support asynchronous context managers , iterators. entering , exiting context manager, or looping on iterator can become more points in co-routine signal other code can run instead because waiting again.
Comments
Post a Comment