Tutorial

Multitasking in Python

2 min read

Multitasking in Python, also known as concurrency or parallelism, refers to the ability of a program to execute multiple tasks concurrently. In Python, there are several ways to achieve multitasking, including threading, multiprocessing, and asynchronous programming.

Threading in Python

Threading is a way to achieve multitasking within a single process. It allows us to run multiple threads of execution concurrently. Each thread represents an independent flow of execution, and the operating system scheduler manages their execution.

Example of Threading in Python:

import threading

def task1():
    for i in range(5):
        print("Task 1 executing")

def task2():
    for i in range(5):
        print("Task 2 executing")

# Create threads
thread1 = threading.Thread(target=task1)
thread2 = threading.Thread(target=task2)

# Start threads
thread1.start()
thread2.start()

# Wait for threads to finish
thread1.join()
thread2.join()

print("All tasks completed")

Here, two tasks (task1 and task2) are defined as separate functions. Two thread objects are created, one for each task. The start() method is called to initiate the execution of the threads. Finally, the join() method is used to wait for the completion of the threads before the program exits.

Multiprocessing in Python

Multiprocessing allows you to achieve true parallelism by executing tasks in separate processes. Each process has its own memory space and runs independently of others.

Example of Multiprocessing in Python:

import multiprocessing

def task1():
    for i in range(5):
        print("Task 1 executing")

def task2():
    for i in range(5):
        print("Task 2 executing")

# Create processes
process1 = multiprocessing.Process(target=task1)
process2 = multiprocessing.Process(target=task2)

# Start processes
process1.start()
process2.start()

# Wait for processes to finish
process1.join()
process2.join()

print("All tasks completed")

Here, similar to threading, two tasks (task1 and task2) are defined as separate functions. Two process objects are created, one for each task. The start() method is used to initiate the execution of the processes. The join() method is called to wait for the processes to finish before the program exits.

Asynchronous Programming in Python

Asynchronous programming is a way to achieve multitasking by allowing tasks to run concurrently without blocking the execution of other tasks. Python provides the asyncio module for asynchronous programming using coroutines and event loops.

Example of Asynchronous Programming in Python:

import asyncio

async def task1():
    for i in range(5):
        print("Task 1 executing")
        await asyncio.sleep(1)

async def task2():
    for i in range(5):
        print("Task 2 executing")
        await asyncio.sleep(1)

# Create an event loop
loop = asyncio.get_event_loop()

# Run the coroutines concurrently
loop.run_until_complete(asyncio.gather(task1(), task2()))

print("All tasks completed")

Here, two asynchronous tasks (task1 and task2) are defined as coroutines using the async keyword. The await keyword is used to suspend the execution of a coroutine temporarily.

The asyncio.sleep() function is used to introduce a delay of one second between each iteration of the tasks. The asyncio.gather() function is used to run the coroutines concurrently.

Is Python programming a real challenge for you? You might be looking for an Online Python Tutor.

 


Leave a Reply

Your email address will not be published. Required fields are marked *