Concurrency is one approach to drastically increase the performance of your Python programs. Concurrency allows several processes to be completed concurrently, maximizing the utilization of your system's resources. Concurrency can be achieved in Python by the use of numerous methods and modules, such as threading, multiprocessing, and asynchronous programming. In this article, we will learn about What is concurrency in Python, the processes required to implement it, some good examples, and the output results.
What is Concurrent Programming?
It refers to the ability of the computer to manage multiple tasks at the same time. These tasks might not be compulsory to execute at the exact same moment but they might interleaved or executed in overlapping periods of time. The main goal of concurrency is to handle multiple user inputs, manage several I/O tasks, or process multiple independent tasks.
What is Parallelism?
Parallelism is a subset of concurrency where tasks or processes are executed simultaneously, As we know concurrency is about dealing with multiple tasks, whereas parallelism is about executing them simultaneously to speed computation. The primary goal is to improve computational efficiency and speed up the [performance of the system.
- Thread-Based Concurrency: Threading is a technique for producing lightweight threads (sometimes known as "worker threads") in a single step. Because these threads share the same memory region, they are ideal for I/O-bound activities.
- Process-Based Concurrency: Multiprocessing entails the execution of several processes, each with its own memory space. Because it can use several CPU cores, this is appropriate for CPU-bound activities.
- Coroutine-Based Concurrency: Asynchronous programming, with 'asyncio' , 'async', and 'await' keywords, is ideal for efficiently managing I/O-bound processes. It enables tasks to pause and hand over control to other tasks during I/O operations without causing the entire program to crash.
Concurrency vs. Parallelism
Concurrency: It refers to the execution of many tasks in overlapping time periods, but not necessarily concurrently. It is appropriate for I/O-bound operations that frequently rely on external resources such as files or network data.
Parallelism: On the other hand, is running many processes at the same time, generally using multiple CPU cores. It is best suited for CPU-intensive jobs requiring lengthy processing.
Steps to Implement Concurrency in Python
- Select the Appropriate Approach:Determine whether your software is CPU or I/O bound. Threading is best for I/O-bound operations whereas multiprocessing is best for CPU-bound workloads.
- Import the Appropriate Libraries: Import the threading, multiprocessing, or asyncio libraries, depending on your method.
- Create Worker Roles: Define the functions or methods that represent the jobs you want to run simultaneously.
- Create Threads, Processes, and Tasks: To execute your worker functions concurrently, create and launch threads, processes, or asynchronous tasks.
- Control Synchronization (if necessary): When employing threads or processes, use synchronization methods such as locks or semaphores to prevent data corruption in shared resources.
- Wait for the job to be finished: Make sure your main application waits for all concurrent jobs to finish before continuing.
Examples of Concurrency in Python
Thread-Based Concurrency
Import the time and threading modules. Print_numbers and print_letters are two functions that simulate time-consuming jobs. To imitate a time-consuming task, these programs print numbers and letters with a 1-second delay between each print. Create two Thread objects, thread1 and thread2, and use the target argument to assign each to one of the functions (print_numbers and print_letters). Use the start() function to start both threads. This starts the parallel execution of the functions. Use the join() method for each thread to ensure that the main thread waits for threads 1 and 2 to finish before continuing. This synchronization step is required to avoid the main program ending prematurely. Finally, print a message indicating that both threads are complete.
Python3
import threading
import time
# Function to simulate a time-consuming task
def print_numbers():
for i in range(1, 6):
print(f"Printing number {i}")
time.sleep(1) # Simulate a delay of 1 second
# Function to simulate another task
def print_letters():
for letter in 'Geeks':
print(f"Printing letter {letter}")
time.sleep(1) # Simulate a delay of 1 second
# Create two thread objects, one for each function
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# Start the threads
thread1.start()
thread2.start()
# The main thread waits for both threads to finish
thread1.join()
thread2.join()
print("Both threads have finished.")
Output:
Printing number 1
Printing letter G
Printing number 2Printing letter e
Printing letter e
Printing number 3
Printing letter kPrinting number 4
Printing letter sPrinting number 5
Both threads have finished.
When you run this code, you'll notice that the two threads execute the two functions, print_numbers and print_letters, concurrently. As a result, the output from both methods will be interleaved, and each function will introduce a 1-second delay between prints, imitating a time-consuming operation. The join() functions ensure that the main program awaits the completion of both threads before printing the final message.
Process-Based Concurrency
Bring the multiprocessing module into the program. Define a square(x) function that squares a given number.Make a number list with the integers [1, 2, 3, 4, 5].Using multiprocessing, create a multiprocessing pool. To manage worker processes, use Pool().Apply the square function to each number concurrently with pool.map() to distribute the work among processes.Get a list of the squared result and then print the values that have been squared
Python3
import multiprocessing
# Function to square a number
def square(x):
return x * x
if __name__ == "__main__":
# Define a list of numbers
numbers = [1, 2, 3, 4, 5]
# Create a multiprocessing pool
with multiprocessing.Pool() as pool:
# Use the map method to apply the 'square ' function to each number in parallel
results = pool.map(square, numbers)
# Print the results
print(results)
Output:
[1, 4, 9, 16, 25]
This code parallelizes the square function on each number, utilizing many CPU cores for quicker execution of CPU-bound operations.
Coroutine-Based Concurrency (using asyncio)
The code is broken down as follows: For asynchronous programming, import the asyncio module.Using await asyncio.sleep(1), define an asynchronous function greet(name) that simulates a greeting with a 1-second delay.Define the asynchronous main function main().To schedule the greet function for each name concurrently, use asyncio.gather().Run the main asynchronous function using asyncio in the if __name__ == "__main__": block.run(main()).
Python3
import asyncio
async def greet(name):
await asyncio.sleep(1)
print(name)
async def main():
await asyncio.gather(greet("Geeks"), greet("For"), greet("Geeks"))
# If in a Jupyter notebook or IPython environment:
import nest_asyncio
nest_asyncio.apply()
if __name__ == "__main__":
asyncio.create_task(main())
Output:
Geeks
For
Geeks
When you run this code, you'll notice that the greet function is called for each name in turn, and it waits 1 second before printing a greeting. The output will show greetings for "Geeks," "For," and "Geeks" in an interleaved fashion, demonstrating the non-blocking nature of Python asynchronous programming.
Finally, whether your programs are I/O-bound or CPU-bound, introducing concurrency in Python can dramatically improve their performance. You may improve the efficiency and responsiveness of your Python programs by selecting the proper technique and leveraging packages such as threading, multiprocessing, and asyncio
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read