Python OOPs


Python SQLite


Examples


Others


Python Thread()


Python's threading module provides a high-level interface for creating and working with threads, enabling you to perform multiple tasks concurrently. Threads are especially useful for I/O-bound tasks like reading files, network operations, or interacting with databases

What is a Thread ?

A thread is a lightweight, smallest unit of a process that can be scheduled to run. Multiple threads within a process share the same memory space, allowing efficient communication but also requiring synchronization to avoid conflicts.

Basic Example of Thread
import threading

def print_numbers():
    for i in range(10):
        print(f"Number: {i}")
        
def print_alphabets():
    for i in range(65,76):
        print(f"Alphabet : "+chr(i))
        
# Create a thread
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_alphabets)

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

# Wait for the thread to complete
thread2.join()
thread2.join()

print("Main thread complete")

Output

Number: 0
Number: 1
Alphabet: A
Number: 2
Alphabet: B
Number: 3
Alphabet: C
Number: 4
Alphabet: D
Number: 5
Alphabet: E
Number: 6
Alphabet: F
Number: 7
Alphabet: G
Number: 8
Alphabet: H
Number: 9
Alphabet: I
Alphabet: J
Alphabet: K
Number: 9
Main thread complete

1) Using threading.Thread with args and kwargs

The args parameter is a tuple containing the arguments to be passed to the target function. it is common to pass arguments to the thread's target function. Python's threading module provides several ways to achieved.

The Thread class allows you to pass arguments to the target function via the args and kwargs parameters.

Example with args:
import threading

def greet(name):
    print(f"Hello, {name}!")

thread = threading.Thread(target=greet, args=("Kumar",))
thread.start()
thread.join()# Wait for the thread to complete
thread.join()

print("Main thread complete")

Output

Hello , Kumar !
Example with kwargs:
import threading

def print_numbers(name, count):
    for i in range(count):
        print(f"{name}: {i}")

# Pass arguments as a dictionary
thread = threading.Thread(target=print_numbers, kwargs={"name": "Subject", "count": 5})
thread.start()
thread.join()

print("Main thread complete")

Output

Subject: 0
Subject: 1
Subject: 2
Subject: 3
Subject: 4

2) Using a class to define a thread behavior

A subclass threading.Thread to define a custom thread class that accepts arguments during initialization.

Syntax
import threading

class MyThread(threading.Thread):
    def __init__(self, name, count):
        super().__init__()
        self.name = name
        self.count = count

    def run(self):
        for i in range(self.count):
            print(f"{self.name}: {i}")

# Create and start a custom thread
thread = MyThread(name="CustomThread", count=5)
thread.start()
thread.join()

Output

CustomThread: 0
CustomThread: 1
CustomThread: 2
CustomThread: 3
CustomThread: 4