The Concept of the Asynchronous Programing in Python
Introduction of the Asynchronous Programing
The propose of the asynchronous programing is to prevent our process from blocking by the file or network I/O operation. In python, we can idle the operation with the I/O bound through the OS until it done with event loop in asyncio module.
What is EventLoop?
Eventloop use the system call such as select
, poll
, epoll
to monitor the state of the I/O operation, while the
python program encounter the specified I/O operation then the task would be pended and handled by the system call. When
the I/O operation is finished and return the results, then the pending task call back function would be invoked and notify
that the task is done.
Concepts of the EventLoop and asyncio Module
Each python thread has only one
EventLoop
.EventLoop
in different threads is a different object, which means it’s a thread-local instanceThe
contextvars.ContextVar
in each task of theEventLoop
has already live in thecontextvars.copy_context()
The
Task
before putting in the EventLoop is calledCoroutine
object,Coroutine
object is the instance of the coroutine function which can be specified byasync def
The I/O asynchronous operation also can execute in thread or process through
loop.run_in_executor()
method which do not handle the I/O bound through system call directly and the object type in the EventLoop isFuture
.
Comparing the Future
and Task
Both are the
awaitable
typeFuture
is the parent class ofTask
The
Task
is represent for the unit of the work scheduled and executed by theEventLoop
Future
is represent for the computation that may have not completed yet