threading — run code concurrently using OS threads.
1import threading2import time34def worker(name, delay):5 for i in range(3):6 time.sleep(delay)7 print(f"{name}: {i}")89# Create threads10t1 = threading.Thread(target=worker, args=("A", 0.5))11t2 = threading.Thread(target=worker, args=("B", 0.3))1213# Start and join14t1.start()15t2.start()16t1.join() # Wait for t117t2.join() # Wait for t21819# Lock for shared resources20counter = 021lock = threading.Lock()2223def increment():24 global counter25 with lock:26 counter += 12728# Thread pool29from concurrent.futures import ThreadPoolExecutor3031with ThreadPoolExecutor(max_workers=4) as executor:32 futures = [executor.submit(worker, f"Thread-{i}", 0.1) for i in range(4)]
GIL consideration: