concurrency
In programming, concurrency refers to the ability of a program to manage multiple tasks simultaneously. This can significantly improve the efficiency and performance of your programs, especially when dealing with I/O-bound tasks.
In Python, you can achieve concurrency through several mechanisms, such as threads, asyncio
, and multiprocessing. While threads and asyncio
allow for concurrent execution in a single process, multiprocessing enables you to run concurrent tasks across multiple processes, taking advantage of multiple CPU cores.
Example
Here’s a simple example using Python’s asyncio
module to run two tasks concurrently:
>>> import asyncio
>>> async def task1():
... for i in range(5):
... print(f'Task 1 - Iteration {i}')
... await asyncio.sleep(1)
...
>>> async def task2():
... for i in range(5):
... print(f'Task 2 - Iteration {i}')
... await asyncio.sleep(1)
...
>>> async def main():
... await asyncio.gather(task1(), task2())
...
>>> asyncio.run(main())
Task 1 - Iteration 0
Task 2 - Iteration 0
Task 1 - Iteration 1
Task 2 - Iteration 1
Task 1 - Iteration 2
Task 2 - Iteration 2
Task 1 - Iteration 3
Task 2 - Iteration 3
Task 1 - Iteration 4
Task 2 - Iteration 4
In this example, task1()
and task2()
are run concurrently, allowing you to perform operations in both tasks without blocking each other.
Related Resources
Tutorial
Speed Up Your Python Program With Concurrency
In this tutorial, you'll explore concurrency in Python, including multi-threaded and asynchronous solutions for I/O-bound tasks, and multiprocessing for CPU-bound tasks. By the end of this tutorial, you'll know how to choose the appropriate concurrency model for your program's needs.
For additional information on related topics, take a look at the following resources:
- Async IO in Python: A Complete Walkthrough (Tutorial)
- An Intro to Threading in Python (Tutorial)
- Speed Up Python With Concurrency (Course)
- Python Concurrency (Quiz)
- Hands-On Python 3 Concurrency With the asyncio Module (Course)
- Async IO in Python: A Complete Walkthrough (Quiz)
- Threading in Python (Course)
- Python Threading (Quiz)
By Leodanis Pozo Ramos • Updated May 6, 2025