← Lessons

quiz vs the machine

Silver1100

Concurrency

The Timed Lock

Acquiring a lock with a deadline so a thread never waits forever.

4 min read · intro · beat Silver to climb

Waiting with a limit

A plain lock call blocks until it succeeds, which can stall a thread indefinitely if the holder misbehaves. A timed lock adds a deadline: acquire the lock or give up after a set duration.

How it behaves

  • The thread tries to take the lock as usual.
  • If the lock is free it returns success right away.
  • If it is held, the thread waits but only up to the timeout.
  • When the timeout expires the call returns failure and the thread runs a fallback path.

This turns a hard block into a decision. The caller can log a warning, retry later, or back off instead of hanging.

Why it helps

Timed locks let a system detect stuck holders and stay responsive. They are common in deadlock avoidance: a thread that cannot get all its locks within the deadline releases what it holds and tries again, breaking circular waits.

Key idea

A timed lock bounds how long a thread waits, converting an indefinite block into a success or timeout so the program can recover instead of hanging.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a timed lock return when the deadline passes?

2. How do timed locks help avoid deadlock?