AlgoViz

Concurrency and shared state

medium 4 min

Two requests can overlap even on one processor.

Video lesson · Chapter 1 of 5

One slot and two clocks

0:00 / 3:13

Concurrency in an LLD round

1:02Reel

Theory

Read or listen first. About 1 min.

What it is

Imagine pausing a handler immediately after it checks the last free slot. Another handler can run that same check while the first still holds its old answer.

Who gets the last permit?

TimeJob ARead 1StartJob BRead 1Start2 running jobs / 1 permit
Both handlers observe one free permit before either records a claim. Two jobs start against a capacity of one.

Why it exists

Capacity is safe when a successful check also spends the permit. Drawing both handlers on one clock exposes the gap where the second job can slip in.

Words to know

Critical section
The part of an operation that competing handlers must coordinate when they touch shared state.

How it works

Step through the idea, or press Play.

Step 1 of 3

Observe. Two handlers see the same free slot.

Understand it

Worked example

Concurrency and shared state in practice

A pool has one slot. A reads one, B reads one, A claims it, then B claims it. Both observations were accurate when made. Put the availability check and claim behind the same admission operation.

Related case

Sharing a worker pool safely

A thumbnail service has eight GPU slots. Two handlers both read “one free” before either records its claim. Which operation needs to be indivisible?

The workshop key rack
The workshop key rack1234567freeSeven machines are busy

Release once after completion.

Sources