Threading

Thou shall NOT mutate shared state without proper synchronization.

Mutating shared state across threads without synchronization can lead to race conditions, corrupted data, and hard-to-debug issues. Always use synchronization mechanisms like locks, atomic variables, or thread-safe collections to ensure consistency and avoid unexpected behavior.

Thou shall minimize the scope of locks.

Keeping critical sections as short as possible reduces contention, improves concurrency, and lowers the risk of deadlocks. Design your locking logic to only protect the necessary code and resources.

Thou shall NOT hold multiple locks without a clear hierarchy.

Acquiring locks in an inconsistent order can cause circular dependencies and lead to deadlocks. Establish and adhere to a strict lock acquisition hierarchy to avoid such issues.

Thou shall prefer immutable data.

Immutable data structures simplify multithreaded programming by eliminating the need for synchronization. They provide safety guarantees because their state cannot change after creation.

Thou shall avoid busy waiting.

Busy waiting wastes CPU cycles and degrades performance. Instead, use condition variables, semaphores, or other signaling mechanisms to synchronize threads efficiently.

Thou shall NOT block the main thread.

Blocking the main thread prevents responsiveness, especially in UI applications. Delegate long-running tasks to background threads or asynchronous processing.

Thou shall use thread pools judiciously.

Thread pools help manage concurrency by reusing threads and limiting their number. Overusing threads or creating too many threads can lead to contention and resource exhaustion.

Thou shall NOT assume thread execution order.

Thread scheduling is non-deterministic and depends on the operating system. Write code that is robust and predictable regardless of the execution order.


Children
  1. Class
  2. Co Routine Scope
  3. Co Routine Waiting on Job to Finish Join
  4. Ref