asynchronous-python

Explore async Python concepts with code examples and tutorials. Covers asyncio and Python features. Let's learn together!

Introduction to Asynchronous Programming

What is asynchronous programming?

Starting with a broad question, aren’t we? Well, when it comes to asynchronous programming, the goal is to execute multiple tasks within our code simultaneously. Think of it like being on a moving train, chatting with friends, and listening to music all at once. This scenario perfectly illustrates the essence of asynchronous action.

Ben Lutkevich says:
Also known as nonblocking code, asynchronous programming provides opportunities for a program to continue running other code while waiting for a long-running task to complete.

Thread vs process, Concurrency vs parallelism, GIL

Thread vs process

Roderick Bauer says:
Threads are the smallest units capable of independent processing, sharing memory within a process. Conversely, a process possesses its own memory and may encompass multiple threads.

Concurrency vs Parallelism

Concurrency involves executing various tasks by alternating between them rapidly through time slicing, whereas parallelism entails executing different tasks simultaneously.
The image says that all
Screenshot from 2024-05-04 20-43-33

GIL

A GIL (global interpreter lock) is a mechanism used in computer-language interpreters to synchronize the execution of threads so that only one native thread can execute basic operations at a time. However use of a global interpreter lock in a language effectively limits the amount of parallelism reachable through concurrency of a single interpreter process with multiple threads.

Event loops and coroutines

Event loops

The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses. Here we see here how it works Screenshot from 2024-05-04 21-47-21

coroutines

Coroutines have been described as “functions whose execution you can pause”.
This seems confusing, but wait, we will clarify it. Anything in Python that can be implemented with the async def statement is a coroutine function.
Here func is a coroutine function:

async def func():
    pass

Then we can run this by awaiting it await func(), or run it from top level by asyncio.run(func()).