# Python Asynchronous Programming (asyncio)

`asyncio` is a library to write concurrent code using the `async`/`await` syntax. It is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.

## Basics

### Coroutines

Coroutines are declared with the `async def` syntax.

```python
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

asyncio.run(main())
```

### Awaitables

We say that an object is an **awaitable** object if it can be used in an `await` expression. There are three main types of awaitable objects: **coroutines**, **Tasks**, and **Futures**.

## Running Concurrent Tasks

The `asyncio.gather()` function allows you to run multiple coroutines concurrently.

```python
import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await asyncio.gather(
        say_after(1, 'hello'),
        say_after(2, 'world')
    )

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())
```

## Creating Tasks

The `asyncio.create_task()` function is used to schedule the execution of a coroutine.

```python
import asyncio

async def my_task():
    print("Task started")
    await asyncio.sleep(1)
    print("Task finished")

async def main():
    task = asyncio.create_task(my_task())
    print("Main continues...")
    await task

asyncio.run(main())
```

[[programming/python/python]]