29. Threading Module

This Python code snippets demonstrating the use of the threading module for implementing multi-threading in Python:

1. Basic Multi-threading

Copy

import threading

def print_numbers():
    for i in range(5):
        print(f"Thread: {threading.current_thread().name} -> {i}")

# Creating threads
thread1 = threading.Thread(target=print_numbers, name="Thread1")
thread2 = threading.Thread(target=print_numbers, name="Thread2")

thread1.start()
thread2.start()

thread1.join()
thread2.join()
print("Execution completed.")

2. Using Thread Class with Arguments

Copy


3. Using a Custom Thread Class

Copy


4. Lock for Thread Synchronization

Copy


5. Using Condition for Thread Communication

Copy


6. Daemon Threads

Copy


7. Thread-safe Queue

Copy


8. Using Event for Thread Signaling

Copy


9. Using Semaphore to Limit Threads

Copy


10. Using Barrier for Thread Coordination

Copy


These examples cover basic threading, synchronization tools (e.g., locks, semaphores, and barriers), communication tools (e.g., events and conditions), and custom thread implementations.

Last updated