Introduction
Threading allows concurrent execution of multiple tasks within the same process.
Basic Threading
import threading
def task(name, delay):
print(f"{name} starting")
time.sleep(delay)
print(f"{name} finished")
# Create threads
t1 = threading.Thread(target=task, args=("A", 1))
t2 = threading.Thread(target=task, args=("B", 2))
# Start and join
t1.start()
t2.start()
t1.join()
t2.join()
Thread Synchronization
# Lock
lock = threading.Lock()
with lock:
shared_counter += 1
# RLock (reentrant lock)
rlock = threading.RLock()
# Semaphore
semaphore = threading.Semaphore(3)
# Event
event = threading.Event()
event.wait(timeout=5)
event.set()
Thread-Safe Data Structures
from queue import Queue
# Thread-safe queue
q = Queue()
q.put(item)
item = q.get()
# With maxsize
bounded_q = Queue(maxsize=10)
Practice Problems
- Create producer-consumer pattern with threads
- Use locks to protect shared resources
- Implement thread pool manually
- Handle Ctrl+C gracefully in threads
- Measure performance with threading