← Lessons

quiz vs the machine

Platinum1830

Concurrency

The Sequence Lock Seqlock

A reader friendly lock where writers never wait on readers.

5 min read · advanced · beat Platinum to climb

Optimized for many readers

A sequence lock, or seqlock, protects data that is read often and written rarely. Its signature property is that readers never block writers and readers take no lock at all. Instead, readers detect when a write happened during their read and simply retry.

How it works

The lock holds a sequence counter, starting even meaning no write in progress.

  • A writer increments the counter to an odd value before writing, does its update, then increments again to an even value. Writers still exclude each other.
  • A reader records the counter, reads the data, then re reads the counter. If the two readings differ, or the start value was odd, a writer was active and the reader retries.

Because readers do not write the counter, they generate no cache line contention among themselves, which is the big win over a reader writer lock under read heavy load.

The limits

  • Readers may retry repeatedly under heavy writing
  • The protected data must be safely re readable with no pointer chasing into freed memory mid read
  • Best for small, frequently read values such as timestamps and counters

Key idea

A seqlock lets readers run lock free and retry on a changed sequence counter, so writers never wait on readers under read heavy load.

Check yourself

Answer to earn rating on the learn ladder.

1. How does a seqlock reader know a write happened during its read?

2. What is the main advantage of a seqlock over a reader writer lock?