A quick look at the event cycle (Event Loop)

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 asynciopackage Advanced APIto start. The asynciomodule 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 asynciopackage provides advanced API, avoid direct use of Event Loopthe 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 APIto meet many usage scenarios, but as a pursuit of apes, should have a little bit of the spirit of exploration, take a look in asynciounder the package Event Loop.

Gets Event Loopthe object
  • asyncio.get_running_loop()
    Get the current system thread is using loopobjects
  • asyncio.get_event_loop()
    Get the current being used by loopthe object. If the current system thread is not loopan object, it will create a new loopobject and use the asyncio.set_event_loop(loop)method to set the current system thread.
  • asyncio.new_event_loop()
    Create a new loopObject
  • asyncio.set_event_loop(loop)
    The loopset target system threads used

Event LoopCommon 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 loopthe object which has APIto understand the underlying implementation details.

Starting and stopping
  • loop.run_until_complete(future)
    futureObject execution is complete before returning
  • loop.run_forever()
    Runs until calling a loop.stop()method
  • loop.stop()
    Stop loopObjects
  • loop.is_running()
    To determine loopwhether you are running
  • loop.is_closed()
    Determine loopwhether to close
  • loop.close()
    Close loopObject
  • coroutine 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 loop callbackmethod, argsis the method parameters
  • loop.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)
    Delay delayseconds after execution
  • loop.call_at(when, callback, *args, context=None)
    At a specified point in time
  • loop.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 of futureobjects
  • loop.create_task(coro)
    Will be coroplaced in scheduling, and returns taskthe object
  • loop.set_task_factory(factory)
    Factory setup tasks
  • loop.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, portand 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 UDPconnection

coroutine loop.create_unix_connection(protocol_factory, path=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)

Create a Unixconnection

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 TCPServices

coroutine loop.create_unix_server(protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)

Creating UnixServices

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

asyncioThe event loop, there are two different implementations: SelectorEventLoopand ProactorEventLooptheir parent isAbstractEventLoop

SelectorEventLoop

This is asyncioused by default Event Loopimplementation, support unixand windowsplatform

import asyncio
import selectors

selector = selectors.SelectSelector()
loop = asyncio.SelectorEventLoop(selector)
asyncio.set_event_loop(loop)
ProactorEventLoop

This is a Windowsplatform-specific implementations

import asyncio
import sys

if sys.platform == 'win32':
    loop = asyncio.ProactorEventLoop()
    asyncio.set_event_loop(loop)

0x01 summary

Event loop is asynciothe core asnciomodule of the many high-level interface is encapsulated by Event Loopthe 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

0x02 quote

  1. https://docs.python.org/3/library/asyncio-eventloop.html

Guess you like

Origin www.cnblogs.com/angrycode/p/11387024.html