About
program ape a thoughtful, lifelong learning practitioners, is currently in a start-up team any team lead, technology stack involves Android, Python, Java, and Go, this is the main technology stack our team.
GitHub: https://github.com/hylinux1024
micro-channel public number: Lifetime developer (angrycode)
0x00 event loop (Event Loop)
Previous article "Why you do not know how to use Python coroutine
" mentioned by the Association process asyncio
package Advanced API
to start. The asyncio
module is the core event loop ( Event Loop
). It can be used to perform asynchronous tasks, event callbacks, perform network IO operation and run sub-process. The official document also recommended that developers should try to use asyncio
package provides advanced API
, avoid direct use of Event Loop
the method object.
Function module underlying capabilities provided by the system such as network connections, and the like are used to file IO loop
.
In most cases, these advanced API
to meet many usage scenarios, but as a pursuit of apes, should have a little bit of the spirit of exploration, take a look in asyncio
under the package Event Loop
.
Gets Event Loop
the object
asyncio.get_running_loop()
Get the current system thread is usingloop
objectsasyncio.get_event_loop()
Get the current being used byloop
the object. If the current system thread is notloop
an object, it will create a newloop
object and use theasyncio.set_event_loop(loop)
method to set the current system thread.asyncio.new_event_loop()
Create a newloop
Objectasyncio.set_event_loop(loop)
Theloop
set target system threads used
Event Loop
Common methods of objects
If you use something like asyncio.run()
these advanced API
, the following methods will be used very seldom, it is recommended to read through it, know about loop
the object which has API
to understand the underlying implementation details.
Starting and stopping
loop.run_until_complete(future)
future
Object execution is complete before returningloop.run_forever()
Runs until calling aloop.stop()
methodloop.stop()
Stoploop
Objectsloop.is_running()
To determineloop
whether you are runningloop.is_closed()
Determineloop
whether to closeloop.close()
Closeloop
Objectcoroutine loop.shutdown_asyncgens()
try:
loop.run_forever()
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
Callback method
loop.call_soon(callback, *args, context=None)
Executed in the next iteration of the event loopcallback
method,args
is the method parametersloop.call_soon_threadsafe(callback, *args, context=None)
Thread-safecall_soon()
iimport asyncio
import time
def hello_world(loop):
print('Hello World')
time.sleep(3) # 模拟长时间操作
loop.stop()
loop = asyncio.get_event_loop()
# 使用loop执行 hello_world()
loop.call_soon(hello_world, loop)
# 会一直阻塞,直到调用了stop方法
try:
loop.run_forever()
finally:
loop.close()
Late callback method
Delaying execution may be provided
loop.call_later(delay, callback, *args, context=None)
Delaydelay
seconds after executionloop.call_at(when, callback, *args, context=None)
At a specified point in timeloop.time()
Returns the current time
import asyncio
import datetime
def display_date(end_time, loop):
print(datetime.datetime.now())
if (loop.time() + 1.0) < end_time:
# 1秒后执行
loop.call_later(1, display_date, end_time, loop)
else:
loop.stop()
loop = asyncio.get_event_loop()
# 执行5秒
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)
# 一直运行,等待stop的调用
try:
loop.run_forever()
finally:
loop.close()
Results of printing time point five seconds
2019-05-09 22:34:47.885412
2019-05-09 22:34:48.887513
2019-05-09 22:34:49.889396
2019-05-09 22:34:50.894316
2019-05-09 22:34:51.898457
Creating Future and Tasks
loop.create_future()
Create a binding event loop offuture
objectsloop.create_task(coro)
Will becoro
placed in scheduling, and returnstask
the objectloop.set_task_factory(factory)
Factory setup tasksloop.get_task_factory()
Return mission factory, it is possible to returnNone
Create a network connection
coroutine loop.create_connection(protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None)
Specify host
, port
and other parameters to create a network connection
coroutine loop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)
Create a UDP
connection
coroutine loop.create_unix_connection(protocol_factory, path=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)
Create a Unix
connection
coroutine loop.create_server(protocol_factory, host=None, port=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)
Creating TCP
Services
coroutine loop.create_unix_server(protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)
Creating Unix
Services
coroutine loop.connect_accepted_socket(protocol_factory, sock, *, ssl=None, ssl_handshake_timeout=None)
Package established connection, returns a tuple(transport, protocol)
Realization of Event Loop
asyncio
The event loop, there are two different implementations: SelectorEventLoop
and ProactorEventLoop
their parent isAbstractEventLoop
SelectorEventLoop
This is asyncio
used by default Event Loop
implementation, support unix
and windows
platform
import asyncio
import selectors
selector = selectors.SelectSelector()
loop = asyncio.SelectorEventLoop(selector)
asyncio.set_event_loop(loop)
ProactorEventLoop
This is a Windows
platform-specific implementations
import asyncio
import sys
if sys.platform == 'win32':
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
0x01 summary
Event loop is asyncio
the core asncio
module of the many high-level interface is encapsulated by Event Loop
the object to achieve. It provides asynchronous task execution, event callbacks, an IO operation and capacity of the network running child processes.
This article is made through official documents a general understanding of the concept of the event loop and its common API. As a "pre-text" supplement