liveBook · Manning

Critical region

As explained in Latency

A critical section is a region of execution that accesses shared state and requires synchronization to prevent conflicting concurrent access.

A critical region is code that accesses shared state and must be synchronized so concurrent threads cannot perform conflicting operations simultaneously. Mutual exclusion allows only one thread to execute the region at a time, preventing race conditions, corruption, inconsistent data, and crashes. section 8.1 section 8.1.1

A shared counter illustrates the boundary: reading or updating the counter belongs inside the protected region, while unrelated work should remain outside it. A mutex or spinlock guards entry; a thread must acquire the lock before accessing the resource. section 8.1 section 8.1.1

Use a critical region safely and efficiently:

  • Protect every access to the shared resource with the same lock. section 8.1
  • Acquire the mutex before entering, perform the required update, and release it immediately afterward. section 8.1.1
  • Keep the region short: blocked threads may enter an OS wait state, adding latency. section 8.1.1
  • Watch for convoying when contention, long regions, or poor scheduling make threads queue behind a delayed lock holder. section 8.2.3

A synchronized counter

In Rust, wrap a counter in std::sync::Mutex. Each of 100 spawned threads calls lock(), increments the counter inside the critical region, and releases the mutex when the guard leaves scope. The shared update is serialized while unrelated thread execution remains concurrent. section 8.1

How Latency covers it

How deep it goes
Defines locking and contention, demonstrates a counter, and discusses convoying, but stops short of lock-internal implementation.
Examples
Uses a shared counter, Rust Mutex code, queued lock holders, and cooperative fibers that avoid yielding during critical sections.
What it assumes
Assumes threads, shared resources, and concurrent access, while defining critical sections and mutex acquisition directly.
What you can do after
Apply mutual exclusion with Rust Mutex to protect shared updates and recognize contention-driven latency risks.
How it connects
Connects critical regions to mutual exclusion, mutexes, race conditions, convoying, fibers, and wait-free synchronization.

Also explained in

Compare how 9 books explain critical region →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Latency. The section links point to the parts of the book it draws on.