Advanced

A lock held across an await

A lock is held for the length of a block. An await inside the block can be a network call, and the lock is then held for the length of a network call.

What you will see

One line. A rule written as a file is a rule that can be checked.

About 1 min of reading

Try It

Measure a hold time

1

Write the hold times

printf '12\n40\n3000\n' > /tmp/h.txt; sort -n /tmp/h.txt | tail -1

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

What it prints
3000. One hold is a network call, and the number says so.
2

Move the await out

printf 'lock 12\nawait 3000 outside\n' > /tmp/h2.txt; awk '{s+=$1} END {print s}' /tmp/h2.txt

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

What it prints
3012 total but the hold is 12. Hold time is what contenders pay, not the total.
3

Write the lint

printf 'rule=no-await-inside-lock\n' > /tmp/r.txt; cat /tmp/r.txt

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

What it prints
One line. A rule written as a file is a rule that can be checked.

Data Flow

A lock to a wait
1 The lock is taken
↓
2 An await runs inside the block
↓
3 The hold time becomes the await time
↓
4 Contenders wait for the hold time
Why this works
Why the hold time is the metric

Hold time times the count of contenders is the wait. The wait is the number that shows up as latency.

The rule for shared state in async

No await inside a lock. The rule is short enough to be a lint, and long enough to be argued.

Examples

The lock is held for a request

Every other task that needs the lock waits for the request. The throughput of the shared part is now one request at a time.

Why the compiler sometimes helps

A lock that crosses an await is a lock that lives in the machine. The type complains when the type can tell.

The fix is a shorter block

Take the value under the lock, release, then await. The await is outside the block, and the block has no await.

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.

← Send and Sync are the contract
Previous Lesson
Send and Sync are the contract
Next Lesson
Crossing the boundary
Crossing the boundary →