Junior — Middle
What methods and tools for implementing parallelism and asynchrony are applicable in Python?
sobes.tech AI
Answer from AI
In Python, several main approaches are used to implement parallelism and asynchrony:
- Multithreading (threading) — allows running multiple threads within a single process. Due to GIL (Global Interpreter Lock) in CPython, threads cannot execute bytecode simultaneously, so multithreading is effective for I/O-bound tasks.
import threading
def worker():
print("Work in thread")
thread = threading.Thread(target=worker)
thread.start()
thread.join()
- Multiprocessing — creates separate processes, each with its own memory, which helps bypass GIL limitations and efficiently utilize multiple CPU cores.
from multiprocessing import Process
def worker():
print("Work in process")
process = Process(target=worker)
process.start()
process.join()
- Asynchronous programming (asyncio) — allows writing non-blocking code using coroutines, event loops, and
async/awaitkeywords. Suitable for a large number of I/O operations.
import asyncio
async def main():
print("Start")
await asyncio.sleep(1)
print("End")
asyncio.run(main())
- Libraries and frameworks — for example,
concurrent.futuresfor easy work with threads and processes,geventortwistedfor cooperative multitasking.
The choice of method depends on the task: for CPU-intensive tasks — multiprocessing, for I/O — threading or asyncio.