Avoiding Deadlock in Common Patterns
Pattern: Nested Locks
Problem: Function A locks X, calls function B, which locks Y. Hidden ordering dependency.
Fix: Document lock dependencies. Ensure all paths acquire X before Y. Or restructure to avoid nesting.
Pattern: Callback While Holding Lock
Problem: Hold lock, call listener/callback. Callback tries to acquire locks, possibly your lock.
Fix: Collect data while holding lock, release lock, then call callbacks. Never call external code while holding locks.
Pattern: Lock Scope Creep
Problem: Lock acquired at start of long function, released at end. Scope grows over time as code is added.
Fix: Minimize lock scope. Acquire late, release early. Use helper methods with clear lock boundaries.
Pattern: Dining Philosophers Style
Problem: Multiple resources, each thread needs multiple, circular dependency possible.
Fix: Global ordering of resources. Or limit concurrent attempts (N-1 philosophers). Or use a single global lock (reduces concurrency).