Python threading example [2 thread objects]

Threading is a powerful technique that allows a program to execute multiple tasks concurrently, making the most of modern multi-core processors. Python, a versatile and widely used programming language, provides the threading module to facilitate the creation and management of threads. Threads are lightweight units of execution that can run independently, making it possible to perform tasks concurrently enhancing program efficiency and responsiveness. In this example, we’ll explore using Python’s threading module to create and coordinate threads, demonstrating the concurrent execution of tasks within a Python program.

Two-Thread Example CODE:

import threading
import time

# Define a simple function that will be executed in a thread
def print_numbers():
    for i in range(1, 6):
        print(f"Number {i}")
        time.sleep(1)

# Define another function to print letters
def print_letters():
    for letter in 'CODE':
        print(f"Letter {letter}")
        time.sleep(1)

# Create two threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)

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

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

print("Both threads have finished.")

In this Threading example, we’re demonstrating concurrent execution of tasks using threads. First, we import the threading module. Then, we define two functions, print_numbers and print_letters, representing tasks we want to perform concurrently.

These functions print numbers(1 to 6) and letters (CODE), respectively, with a 1-second pause between prints to simulate work. We create two thread objects (thread1 and thread2) and assign the target functions.

After starting both threads with start(), they run concurrently, performing their respective tasks. We use join() to wait for both threads to complete their work before printing a message confirming their finish.

Running the script.

When you run the scripts, it will provide the output:

python .\demo_threading.py
Number 1
Letter C
Letter O
Number 2
Number 3
Letter D
Letter E
Number 4
Number 5
Both threads have finished.

In conclusion, the Threading module offers a convenient way to harness the power of multithreading, enabling developers to execute multiple tasks in parallel and improve program performance efficiently. By carefully managing threads and synchronization, you can create responsive and efficient applications capable of handling diverse workloads.