# The Concept of the Asynchronous Programing in Python


<!--more-->

## 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 instance

* The `contextvars.ContextVar` in each task of the `EventLoop` has already live in the `contextvars.copy_context()`

* The `Task` before putting in the EventLoop is called `Coroutine` object, `Coroutine` object is the instance of the 
  coroutine function which can be specified by `async 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 is `Future`.

## Comparing the `Future` and `Task`

* Both are the `awaitable` type

* `Future` is the parent class of `Task`

* The `Task` is represent for the unit of the work scheduled and executed by the `EventLoop`

* `Future` is represent for the computation that may have not completed yet

## Reference

[Python Asyncio: The Complete Guide](https://superfastpython.com/python-asyncio/)

[Youtube: import asyncio: Learn Python's AsyncIO](https://youtu.be/E7Yn5biBZ58?t=947)

