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()