Asyncio
coroutines
使用async/await
函数称为coroutinefunction
函数调用返回的称为coroutine object, 一般当读说coroutine都是指代coroutine object
内部使用使用的generator/yield/yield from,但是为了概念的划分而单独区分开来.
旧版本中使用@asyncio.coroutine装饰器将一个generator函数表述为coroutine function.(Will be removed.)
Awaitables:
- coroutine object
- Future 使用 生成 low level
- Task high level
asyncio.run(main())生成一个loop, 并run loop. 只能用一次,用于最外层的coroutineasyncio.ensure_futures(coro)生成一个Future, 在get_running_loop()中执行asyncio.create_task(coro)生成一个Task, 在get_running_loop()中执行awaitable asyncio.gather(*aws, loop=None, return_exceptions=False)coroutine自动包装为Task并执行
for taks in asyncio.all_tasks():task.cancel()await asyncio.gather(*tasks, return_exceptions=True)
coroutine asyncio.wait_for(aw, timeout, *, loop=None)cancel when timeoutcoroutine asyncio.wait(aws, *, loop=None, timeout=None, return_when=ALL_COMPLETED)do not cancel when timeoutFIRST_COMPLETEDFIRST_EXECUTIONALL_COMPLETED
asyncio.as_completed(aws, *, loop=None, timeout=None)return a generated, each Future returned represents the earliest result from the set of remaining awaitables.
for f in as_completed(aws):earliest_result = await f
Task
asyncio.current_taskasyncio.all_tasks
Stream
top level asyncio functions based on loop.create_connection and loop.create_server
coroutine asyncio.open_connection(host=None, port=None, *, loop=None, limit=None, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None)- Establish a network connection and return a pair of (reader, writer) object
coroutine asyncio.start_server(client_connected_cb, host=None, port=None, *, loop=None, limit=None, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True)client_connected_cbis a function or coroutine function receive (reader, writer) as parameters. if a coroutine function , it wiil be automatrically scheduled as a Task when server a client.
coroutine asyncio.open_unix_connection(path=None, *, loop=None, limit=None, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)coroutine asyncio.start_unix_server(client_connected_cb, path=None, *, loop=None, limit=None, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)- Can bind to a existing socket. For example:
rsock, wscok = scoket.socketpair()
asyncio.StreamWriter
write/writelinescorourine drainShould be used afer write/writelines. Blocks until the size of the buffer is drained down to the low watermark.write_eofclose the write end of the stream afetr the bufered write data is flushed.closecoroutine wait_closedShould be used afer close. Wait until the underlying connection is closedget_extra_info('peername')
asyncio.StreamReader
coroutine read(n=-1)coroutine readline()coroutine readuntil(separator=b'\n')- Be cautious about
EOF.
Synchronizarion
Not thread safe, Use threading otherwise.
asyncio.Lock
couroutine acquirereleaselockedreturn True if lock is locked.
lock = asyncio.Lock()async with lock:pass# Equal toawait lock.acquire()try:passfinally:lock.release()
asyncio.Event
Like a awaitable flag with True/False flag.
coroutine wait()wait to be setted.set()clear()is_set()return True if setted.
asyncio.Condition
similar to lock
asyncio.Semaphore(value=1)
A waitable counter. Decremented by each acquire() and incrementedby each release(). Can never go below zero.acqure() blocks when counter is 0.
coroutine acquirereleaselocked
asyncio.BoundedSemaphore(value=1)
Raises ValueError in release() when the counter above the initial value after release.
asyncio.Queue(maxsize=0)
asyncio.PriorityQueue(maxsize=0)
- items are tuples (priority_number, data)
asyncio.LifoQueue(maxsize=0)
maxsize/empty()/full()/qsize()coroutine get()blocks when an item is availablecoroutine put(item)blocks when queue fullget_nowait()/put_nowait()Non block version.Raiseasyncio.QueueEmptyorasycio.QueueFullrespectivelytask_done()inform a task fetched from queue is done.coroutine join()wait until the number(all enqueued items) of times task_done has been called.
Event Loop
low level network handling
- create_connection return a pair of (Transport, Protocol)
- create_server return a Server object
coroutines.iscoroutine
- coroutine
- generator
…
_COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,collections.abc.Coroutine, CoroWrapper)def iscoroutine(obj):if isinstance(obj, _COROUTINE_TYPES):# .......return Trueelse:return False
futures.isfuture
sublcass of Future or containing a class data
def isfuture(obj):return (hasattr(obj.__class__, '_asyncio_future_blocking') andobj._asyncio_future_blocking is not None)
inspect.isawatable
- coroutine(async def)
- types.coroutine decorated generator object
- subclass of collections.abc.Awaitable
def isawaitable(object):"""Return true if object can be passed to an ``await`` expression."""return (isinstance(object, types.CoroutineType) orisinstance(object, types.GeneratorType) andbool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) orisinstance(object, collections.abc.Awaitable))
class Future(object):def set_result(self, res):self.result = resself.schedule_callbacks()def add_done_callback(self, cb):passdef schedule_callbacks(self):for cb in self.callbacks:loop.call_soon(cb)class Task(object):def __init__(self, coro):self.coro = coroself.step()def step(self, exc):try:res = self.coro.send(None)if futures.isfuture(res):res.add_done_callback(self.step)except StopIteration as exc:super().set_result(exc.value)
futures
a representaion of state
Can not self-wake-up. Thus, by any way, all Futures needs to be within a Task.
A Furture must coexist with a io event(directly or indirectly) or a schecdule event like call_soon call_later
Cancel a future has two cases:
set_result called after outer task’s cancel, then the final state of this Future is CANCELLED, so self.result() will raise Cancelled error, and cause in await future.
set_result called before outer task’s cancel, then the final state of this Future is FINISHED, however, as task._must_cancel is True, taks.step will call coro.throw thus raise Cancelled error when resuming from yield self, then catched in await future.
task
a representaion of process(coroutine) state, wrapper of a coroutine(a precess), The state of process is represented as a set of Future yielded within the coroutine.
self wakable coroutine. Wake up(send(None)) the the paused coroutine by adding step callback to the yielded Future object
class Future:def __await__(self):if not self.done():self._asyncio_future_blocking = Trueyield self # This tells Task to wait for completion.if not self.done():raise RuntimeError("await wasn't used with future")return self.result() # May raise too.class Task(Future):def cancel(self, msg=None):self._log_traceback = Falseif self.done():return Falseif self._fut_waiter is not None:if self._fut_waiter.cancel(msg=msg):return Trueself._must_cancel = Trueself._cancel_message = msgreturn True
Main diagram:
step in Task. init will be called when a task is created
Coroutine within the task will be triggered by coro.send(None) in step
Coroutine runs and is paused at some yield position(yield a Future)
set_result function of this Future registered at some IO event will be called
set_result will trigger the call of done_callback added by the outer task
step in done_callback will call coro.send(None),
current_task
enter_task and leave_task will be called before and after coro.send().
thus this data can be used within a coroutine and findout the outer task
asyncio.gather function
return a future, results is a list containing all results of children task/future(ensure_futured)
since it’s a future, itself needs to be within a task.
asyncio.wait async function
return twos lists of done futures and pending futures
asyncio.ascopleted generator function
generate coroutines, await these coroutine can get results of input futures
asyncio.shild return a future ?????
queue
Use deque or list or heapq as the item container
# no matter a cancel is happend before or after put_nowait, the next getter will be released.# case1tget1.cancel() # since getter is pending, will set canceled sucessfulyq.put_noawait() # will pass the firs getter as it's already done, so the second getter will be set# and will raise CancelledError when the first getter resumes, however since it's cancelled,# the last if statement will not pass, thus no wake_up_next will be calledawait asyncio.sleep(1)# case2q.put_nowait() # set the first gettertget1.cacel()await asyncio.sleep(1)# all Cancelled error will reraised and cathced by step function in Task, then it just simply igore it
def _wakeup_next(self, waiters):while waiters:waiter = waiters.popleft()if not waiter.done():waiter.set_result(None)breakdef put_nowait(self, item):if self.full():raise QueueFullself._wakeup_next(self._getters)async def get(self):while self.empty():getter = self._loop.create_future()self._getters.append(getter)try:await getter # put_noawait will set_result(None)except:# incase of the task(containing await q.get) is cancelled, will raise CancelledError(comes from throw(err)).# Even through, getter's state is FINISHED and with no exceptiongetter.cancel() # Just in case getter is not done yet.try:# Clean self._getters from canceled getters.self._getters.remove(getter)except ValueError:# The getter could be removed from self._getters by a# previous put_nowait call.pass# normally getter will always be FINISHED. so (not getter.cancelled()) is Trueif not self.empty() and not getter.cancelled():# We were woken up by put_nowait(), but can't take# the call. Wake up the next in line.self._wakeup_next(self._getters)raisereturn self.get_nowait()
lock
asyncio.Lock
async def acquire(self):if (not self._locked and (self._waiters is None orall(w.cancelled() for w in self._waiters))):self._locked = Truereturn Trueif self._waiters is None:self._waiters = collections.deque()fut = self._loop.create_future()self._waiters.append(fut)try:try:await futfinally:self._waiters.remove(fut)except exceptions.CancelledError:if not self._locked:self._wake_up_first()raiseself._locked = Truereturn Truedef release(self):if self._locked:self._locked = Falseself._wake_up_first()else:raise RuntimeError('Lock is not acquired.')def _wake_up_first(self):if not self._waiters:returntry:fut = next(iter(self._waiters))except StopIteration:return# if this fut is CANCELLED, then next step will throw CancelledError in fut's __await__,# then will be catched in resumed acquare, then falls agin in this function# if this fut is FINISHED, no need to set_result againif not fut.done():fut.set_result(True)
protocols
为抽象接口,底层的IO在触发相应的事件后会调用相应的接口
connection_made
data_received
eof_received
connection_lost
transport的write buffer在高位和地位的时候会调用这两个函数
pause_writing
resume_writing
总之,write的buffer时间在内核,而read的buffer是现在应用层,存在buffer的地方可以通过调用相应的函数来通告另一方暂停或者继续
streams
FlowControlMixin(Protocol)
主要控制与write相关的流程
pasuse_writing/resume_writing操控self._drain_waiter,_data_helper()生成_drain_waiter并阻塞写
connnection_lost与resume_writing都会set_result self._dain_waiter
SteamReader()
实现各种读的接口,数据的来源都是来源于protocol.data_received()
实现了读的buffer,通过, feed_data/feed_eof 控制self._waiter, _wait_for_data生成_waiter并阻塞读,feed_data的时候检测buffer总大小,如果超过一定值则调用self._transport.pause_reading进行暂停读取
注意的是,不能直接读取数据,通过feed函数供给protocol的data_received进行调用
StreamReaderProtocol(FlowControlMixin)(reader, client_connected_cb)
connection_made(transport)
设置reader.transport
如果client_connected_cb存在话,CreateTask(cb),并且生成write
data_received,connection_lost,eof_received都需要调用reader的feed_data()/feed_oef()进行传输可读取的数据
StreamWriter(transport, protocoll, reader)
实现各种写的接口,但都是直接通过transort进行调用
drain用于阻塞write,内部是调用protocol._drain_helper,内部是只有protocol.resume_writing被调用后,drain_waiter才会被set_result
coroutines
inspect
def isgeneratorfunction(object):return bool((isfunction(object) or ismethod(object)) andobject.__code__.co_flags & CO_GENERATOR)def iscoroutinefunction(object):return bool((isfunction(object) or ismethod(object)) andobject.__code__.co_flags & CO_COROUTINE)def isgenerator(object):return isinstance(object, types.GeneratorType)def iscoroutine(object):return isinstance(object, types.CoroutineType)def isawaitable(object):"""Return true if object can be passed to an ``await`` expression."""return (isinstance(object, types.CoroutineType) orisinstance(object, types.GeneratorType) andbool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) orisinstance(object, collections.abc.Awaitable))
_COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,collections.abc.Coroutine, CoroWrapper)_iscoroutine_typecache = set()def iscoroutine(obj):if isinstance(obj, _COROUTINE_TYPES):return Trueelse:return False
events
AbstractEventLoop
BaseDefaultEventLoopProlicy
Handle
TimerHandle(Handle)
base_events
BaseEventLoop(events.AbstractEventLoop)
run_in_executor
调用futures.wrap_future,将threadPool里的concurrent.Future与新生成的Future绑定,给两者加上done_callback,任何一方done后会激活另一方done
sock_sendfile
内部会调用run_in_executor不断的把文件读进memoryview中,之后再调用sock_sendall()
get_addrinfo/nameinfo
都是调用的run_in_executor
create_connection
先通过get_addrinfo获取host ips,从第一个ip开始,绑定local ip/port(有必要的话),建立连接后break
另外还支持happy_eyeball,可以自动选择ipv4/ipv6连接(调用staggered.staggered_race)
获得建立连接的socket后
transport, protocol = await self._create_connection_transport(socket, protocol_factory,ssl)
_create_connection_transport
socket.setblocking(False)
protocol = protocol_factory()
transport = self.make_transport(socket, protocol) 会区分有没有ssl
await 一个新生成的Future
create_datagram_endpoint
与SOCK_STREAM相比,多了reuse_port,allow_broadcast选项
与create_connection一样,也会创建protocol,transport和一个新的Future
create_server
支持绑定多个host,会生成多个sockets
支持reuse_addr, reuse_port
之后创建一个server
server = Server(self, sockets, protocol_factory, ssl)
server._start_serving
socket.listen()
loop._start_serving(protocol_factory, socket)
await asyncio.sleep()
_run_once
调度器主要的循环单元
- 移除cancelled schedules
- 在一定的timeout内将selectIO事件的reader/writer(都是Handle对象)加入到_ready队列中
- selector注册的时候为
- 将schedulu中到期handle转移到_ready队列中
- 调用所有_ready中的非cancelled handle的_run()函数
- Handle._run() 调用Hanhel._callback
unix_events
包含真正的evenloopPolicy 和EventLoop
eventloop由self._loop_factory生成
_loop_factory为unix下的SelectoEventLoop 或者windows下的ProactorEventloop
sock_connect
- socket.connect
- 生成Future
- add_writer
- _add_reader/writer就是注册不同的事件,将Handle注册为event.data,每个Handle的_callback就是set_resultFuture
- Fut.add_done_callback 是remove_writer
- await Future
- 当Future done时,表示建立连接,create_connection 完毕
create_sock_transport
socket已经建立连接(write事件已结束)
接受scoket,空protocol,loop
_start_serving
_add_reader(fd, self._accept_connection, protocol_factory, sock, sslcontext, server)
_accept_connection
socket.accept
create_task(self._accept_connection2(pf, conn, extra, sslcontext, server))
_accept_connection2
protocol = pf()
waiter = self.create_future()
transport = self.mak_socket_transport()
await waiter
SelectorTransport
init
disable Nagle algorithm
call_soon(protocol.connection_made)
call_soon(loop.add_reader)
call_soon(waiter) 目的是在connection_made调用后才返回transport 和protocol
