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.
import threading
def print_range(start, end):
for i in range(start, end):
print(f"Range {start}-{end}: {i}")
thread = threading.Thread(target=print_range, args=(1, 6))
thread.start()
thread.join()
import threading
class CustomThread(threading.Thread):
def run(self):
for i in range(3):
print(f"Custom thread: {self.name} -> {i}")
thread = CustomThread()
thread.start()
thread.join()
import threading
counter = 0
lock = threading.Lock()
def increment_counter():
global counter
with lock:
for _ in range(10000):
counter += 1
threads = [threading.Thread(target=increment_counter) for _ in range(5)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(f"Final Counter Value: {counter}")
import threading
import time
semaphore = threading.Semaphore(2)
def limited_access_task(thread_id):
with semaphore:
print(f"Thread-{thread_id} acquiring semaphore")
time.sleep(1)
print(f"Thread-{thread_id} releasing semaphore")
threads = [threading.Thread(target=limited_access_task, args=(i,)) for i in range(5)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
import threading
barrier = threading.Barrier(3)
def wait_at_barrier(thread_id):
print(f"Thread-{thread_id} waiting at barrier")
barrier.wait()
print(f"Thread-{thread_id} passed the barrier")
threads = [threading.Thread(target=wait_at_barrier, args=(i,)) for i in range(3)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()