Advanced

Send and Sync are the contract

A task that moves to another thread carries its captures with it. The compiler checks that carrying with two words, and the two words are the contract of the executor.

What you will see

One line. Sync is a claim about shared state, so shared state is named.

About 1 min of reading

Try It

Name the shared parts

1

Write the captures

printf 'config owned\nsocket reference\n' > /tmp/c.txt; grep reference /tmp/c.txt

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

What it prints
socket reference. That line is the capture that breaks Send.
2

Copy instead of reference

printf 'config owned\nsocket owned\n' > /tmp/c2.txt; grep -c reference /tmp/c2.txt

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

What it prints
0. Zero references means the task can move, which is what the bound checks.
3

Name the shared state

printf 'shared=counter sync=yes\n' > /tmp/s.txt; cat /tmp/s.txt

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

What it prints
One line. Sync is a claim about shared state, so shared state is named.

Data Flow

A capture to a spawn decision
1 The task captures its values
↓
2 Each capture is checked for Send
↓
3 Shared parts are checked for Sync
↓
4 The spawn is allowed or refused
Why this works
The shape that breaks Send

A reference into a non-shareable resource. The reference is the thing that cannot be carried, and the resource is the reason.

What the bound does not promise

It promises moving is legal. It does not promise the moved task is correct, which is a test.

Examples

Send means it can move

A capture that cannot be moved makes the whole task unable to move. The error names the capture, not the task.

Sync means shared is safe

Shared state must be safe from more than one thread. The bound is on the shared part, not on the task.

Why the error is a good one

The compile fails before the race exists. A race found in review is a race found by luck.

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.

← Recursion inside async
Previous Lesson
Recursion inside async
Next Lesson
A lock held across an await
A lock held across an await →