Basic

Shared state in a server

Handlers run at the same time. Anything they share has more than one writer, and more than one writer is a decision about who is allowed to write.

What you will see

One line. A mechanism without its count is a mechanism nobody can argue with.

About 1 min of reading

Try It

Count the writers

1

Write the shared values

printf 'config 0\ncounter 1\ncache 3\n' > /tmp/v.txt; awk '{print $1, $2}' /tmp/v.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Three lines. The writer count is the input to the mechanism choice.
2

Choose from the count

awk 'BEGIN {for (w=0;w<3;w++) print w, (w==0 ? "immutable" : w==1 ? "atomic" : "lock")}'

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0 immutable, 1 atomic, 2 lock. The count decides, not the habit.
3

Write the choice with the count

printf 'cache writers=3 mechanism=lock\n' > /tmp/c.txt; cat /tmp/c.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
One line. A mechanism without its count is a mechanism nobody can argue with.

Data Flow

A value to a writer count
1 The value is declared
↓
2 The writers are counted
↓
3 The mechanism is chosen from the count
↓
4 The choice is written with the count
Why this works
Why the default is immutable

Most of what a server reads is decided at start. Decided at start means never written, which means no race.

The one question to ask

How many writers. Zero writers is free, one writer is a queue, many writers is a merge.

Examples

Immutable is the default

Config is read and never written. A read that cannot be written has no race to lose.

Atomic is a narrow claim

One counter is atomic because one word is enough. A structure is not one word, and the claim stops there.

A lock is a hold time

The lock is held for the length of the work. The work is the thing that decides the wait.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Decoding into a shape
Previous Lesson
Decoding into a shape
Next Lesson
Headers are a small contract
Headers are a small contract →