Concurrent execution in Python refers to the ability of a program to manage multiple tasks at once. While Python has limitations due to the Global Interpreter Lock (GIL), it offers powerful modules and techniques to achieve concurrency using threads, processes, and asynchronous programming.
Concurrency is useful for:
Python provides three main approaches to concurrent execution:
A thread is the smallest unit of a process that can be scheduled independently by the operating system. Multiple threads within a process share memory and resources.
Pythonβs built-in threading module allows you to create and manage threads easily.
import threading
import time
def print_numbers():
for i in range(5):
print(f"Number: {i}")
time.sleep(1)
t1 = threading.Thread(target=print_numbers)
t1.start()
t1.join()
print("Finished")
Use Lock to prevent race conditions:
lock = threading.Lock()
def update():
with lock:
# critical section
pass
Due to the Global Interpreter Lock (GIL), Python threads do not execute in true parallel fashion on multiple CPUs. They are suitable for I/O-bound tasks, not CPU-bound tasks.
Multiprocessing involves running multiple processes simultaneously, each with its own Python interpreter and memory space. It is ideal for CPU-bound tasks.
Python's multiprocessing module allows the spawning of independent processes.
import multiprocessing
import time
def square(n):
print(f"Square: {n*n}")
if __name__ == "__main__":
p = multiprocessing.Process(target=square, args=(5,))
p.start()
p.join()
def square(n):
return n * n
if __name__ == "__main__":
with multiprocessing.Pool(4) as pool:
results = pool.map(square, [1, 2, 3, 4, 5])
print(results)
asyncio is a library for writing concurrent code using the async/await syntax. It is best suited for I/O-bound and high-level structured network code.
Asyncio uses an event loop to manage and schedule tasks.
import asyncio
async def greet():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(greet())
async def task(name):
print(f"Start: {name}")
await asyncio.sleep(2)
print(f"End: {name}")
async def main():
await asyncio.gather(task("A"), task("B"))
asyncio.run(main())
| Method | Best For | Parallelism | Shared Memory | Example Use Case |
|---|---|---|---|---|
| Threading | I/O-bound tasks | No (due to GIL) | Yes | Reading multiple files |
| Multiprocessing | CPU-bound tasks | Yes | No | Data processing, simulations |
| Asyncio | I/O-bound async tasks | No | Yes (in single thread) | Web servers, API clients |
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
urls = ['https://example.com', 'https://example.org']
tasks = [fetch(url) for url in urls]
responses = await asyncio.gather(*tasks)
print(responses)
asyncio.run(main())
import multiprocessing
import gzip
import shutil
import os
def compress_file(filename):
with open(filename, 'rb') as f_in:
with gzip.open(filename + '.gz', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
if __name__ == "__main__":
files = os.listdir('.')
with multiprocessing.Pool() as pool:
pool.map(compress_file, files)
Thread-safe queues can be used for communication between threads:
import threading
import queue
q = queue.Queue()
def producer():
for i in range(5):
q.put(i)
print(f"Produced {i}")
def consumer():
while not q.empty():
item = q.get()
print(f"Consumed {item}")
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
t1.join()
t2.start()
t2.join()
Pythonβs concurrent.futures module simplifies multithreading and multiprocessing using high-level abstractions.
from concurrent.futures import ThreadPoolExecutor
def task(n):
return n * n
with ThreadPoolExecutor(max_workers=3) as executor:
results = executor.map(task, [1, 2, 3])
for result in results:
print(result)
from concurrent.futures import ProcessPoolExecutor
def task(n):
return n * n
with ProcessPoolExecutor(max_workers=3) as executor:
results = executor.map(task, [1, 2, 3])
for result in results:
print(result)
Concurrent execution is a cornerstone of modern programming. In Python, you can achieve concurrency using multithreading, multiprocessing, or asynchronous programming with asyncio. Each approach has its strengths and weaknesses:
Understanding the principles of concurrency and how to apply them in Python enables developers to build efficient, responsive, and scalable applications.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved