Cheat Sheet For Python Threading
Cheat Sheet For Python Threading
Create, run target function Mutex lock, context manager Wait on condition to be notified (blocking)
thread = Thread(target=task) lock = Lock() with condition:
with lock: condition.wait()
Config thread name # ...
thread = Thread(name=’MyThread’) Wait on condition for expression (blocking)
Reentrant mutex lock, protect critical section with condition:
Config daemon thread (background thread) lock = RLock() condition.wait_for(check)
thread = Thread(daemon=True) with lock:
with lock: Notify any single thread waiting on condition
Extend thread # ... with condition:
class CustomThread(Thread): condition.notify(n=1)
def run(): Semaphore, set num positions
# ... semaphore = Semaphore(10) Notify all threads waiting on condition
semaphore.acquire() with condition:
Start thread (non-blocking) # ... condition.notify_all()
thread.start() semaphore.release()
Barrier, set number of parties
Join thread, wait to finish (blocking) Semaphore, context manager barrier = Barrier(5)
thread.join() semaphore = Semaphore(10)
with semaphore: Arrive and wait at barrier (blocking)
Join thread with timeout # ... barrier.wait()
thread.join(timeout=5)
Create event, then set event Arrive and wait at barrier with timeout
Check if thread is running (not finished) event = Event() barrier.wait(timeout=0.5)
if thread.is_alive(): event.set()
# ... Timer Thread
Check if event is set Wait some time then execute the target function.
Check if daemon (background) if event.is_set():
if thread.daemon: # ... Create timer thread
# ... tmr = Timer(5, task, args=(a1,a2))
Wait for event to be set (blocking)
Access or change thread name event.wait() Start timer thread
thread.name thread.start()
Wait for event with timeout
Access thread native identifier if event.wait(timeout=0.5): Cancel timer thread
thread.native_id # ... thread.cancel()