-
Notifications
You must be signed in to change notification settings - Fork 294
Rewrite atomics section #378
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SabrinaJewson
wants to merge
35
commits into
rust-lang:master
Choose a base branch
from
SabrinaJewson:atomics
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
0347b01
Write “Multithreaded Execution” and add simplified atomic spec
SabrinaJewson 42f46d2
Fix one broken link
SabrinaJewson 46f31ae
Replace accidental rs code blocks with rust
SabrinaJewson 103a733
Replace reads with explicit `println!`s
SabrinaJewson a26eab4
Write the “Relaxed” section
SabrinaJewson d01fb66
Remove specification chapter
SabrinaJewson 715e67f
Write about `Acquire` and `Release`
SabrinaJewson afe0ee2
Write the `SeqCst` section
SabrinaJewson c1129e3
“happens before” → “happens-before”
SabrinaJewson b896399
Introduce synchronizes-with terminology
SabrinaJewson 59fde6f
Use “coherence” terminology from the start
SabrinaJewson 6dc3d54
Remove old sections and introduce “AM” in intro
SabrinaJewson 29707ee
“isomorphic” → “functionally equivalent”
SabrinaJewson 52d5d13
Define the term “race condition”
SabrinaJewson 40b06fe
Add note about duplication of `1` in M.O.
SabrinaJewson 390754b
Explain the ABA problem
SabrinaJewson 493c671
Dispel the myth that RMWs “see the latest value”
SabrinaJewson dc6a942
Explain the C++20 release sequence changes
SabrinaJewson b3c2e62
Explain the Abstract Machine
SabrinaJewson a9eb1f6
Improve the explanations of coherence
SabrinaJewson 8068390
Show the final correct execution in mutex example
SabrinaJewson 3c76e35
Add a more formal explanation of happens-before
SabrinaJewson d4f8f47
Write about acquire and release fences
SabrinaJewson 5e27ed5
Improve the `SeqCst` explanation
SabrinaJewson 805070e
Write about `SeqCst` fences
SabrinaJewson c19184a
Fix Unicode art incorrectly interpreted as Rust code
SabrinaJewson 2384caa
Define “unsequenced” early on
SabrinaJewson d9dabf4
Note that a release fence followed by multiple stores is not necessar…
SabrinaJewson 09c428e
Remove the signals section for now
SabrinaJewson ff32f70
Fix CI
SabrinaJewson af524a5
Fix typos
SabrinaJewson f3277bf
Mention that Rust atomics correspond to `atomic_ref`
SabrinaJewson 6d16ea5
Explain the terms “strongly/weakly-ordered hardware”
SabrinaJewson 19b059a
Merge branch 'master' into atomics
SabrinaJewson b139a3c
Simplify SeqCst demonstration, and remove incorrect claim
SabrinaJewson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# Acquire and Release |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# Fences |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,220 @@ | ||
# Multithreaded Execution | ||
|
||
The first important thing to understand about C++20 atomics is that **the | ||
abstract machine has no concept of time**. You might expect there to be a single | ||
global ordering of events across the program where each happens at the same time | ||
or one after the other, but under the abstract model no such ordering exists; | ||
instead, a possible execution of the program must be treated as a single event | ||
that happens instantaneously — there is never any such thing as “now”, or a | ||
“latest value”, and using that terminology will only lead you to more confusion. | ||
(Of course, in reality there does exist a concept of time, but you must keep in | ||
mind that you’re not programming for the hardware, you’re programming for the | ||
AM.) | ||
SabrinaJewson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
However, while no global ordering of operations exists _between_ threads, there | ||
does exist a single total ordering _within_ each thread, which is known as its | ||
_sequence_. For example, given this simple Rust program: | ||
|
||
```rs | ||
println!("A"); | ||
println!("B"); | ||
``` | ||
|
||
its sequence during one possible execution can be visualized like so: | ||
|
||
```text | ||
╭───────────────╮ | ||
│ println!("A") │ | ||
╰───────╥───────╯ | ||
╭───────⇓───────╮ | ||
│ println!("B") │ | ||
╰───────────────╯ | ||
``` | ||
|
||
That double arrow in between the two boxes (`⇒`) represents that the second | ||
statement is _sequenced after_ the first (and similarly the first statement is | ||
_sequenced before_ the second). This is the strongest kind of ordering guarantee | ||
between any two operations, and only comes about when those two operations | ||
happen one after the other and on the same thread. | ||
|
||
If we add a second thread to the mix: | ||
|
||
```rs | ||
// Thread 1: | ||
println!("A"); | ||
println!("B"); | ||
// Thread 2: | ||
eprintln!("01"); | ||
eprintln!("02"); | ||
``` | ||
|
||
it will simply coexist in parallel, with each thread getting its own independent | ||
sequence: | ||
|
||
```text | ||
Thread 1 Thread 2 | ||
╭───────────────╮ ╭─────────────────╮ | ||
│ println!("A") │ │ eprintln!("01") │ | ||
╰───────╥───────╯ ╰────────╥────────╯ | ||
╭───────⇓───────╮ ╭────────⇓────────╮ | ||
│ println!("B") │ │ eprintln!("02") │ | ||
╰───────────────╯ ╰─────────────────╯ | ||
``` | ||
|
||
Note that this is **not** a representation of multiple things that _could_ | ||
happen at runtime — instead, this diagram describes exactly what _did_ happen | ||
when the program ran once. This distinction is key, because it highlights that | ||
even the lowest-level representation of a program’s execution does not have | ||
a global ordering between threads; those two disconnected chains are all there | ||
is. | ||
|
||
Now let’s make things more interesting by introducing some shared data, and have | ||
both threads read it. | ||
|
||
```rs | ||
// Initial state | ||
let data = 0; | ||
// Thread 1: | ||
data; | ||
// Thread 2: | ||
data; | ||
``` | ||
|
||
Each memory location, similarly to threads, can be shown as another column on | ||
our diagram, but holding values instead of instructions, and each access (read | ||
or write) manifests as a line from the instruction that performed the access to | ||
the associated value in the column. So this code can produce (and is in fact | ||
guaranteed to produce) the following execution: | ||
|
||
```text | ||
Thread 1 data Thread 2 | ||
╭──────╮ ┌────┐ ╭──────╮ | ||
│ data ├╌╌╌╌┤ 0 ├╌╌╌╌┤ data │ | ||
╰──────╯ └────┘ ╰──────╯ | ||
``` | ||
|
||
That is, both threads read the same value of `0` from `data`, with no relative | ||
ordering between them. This is the simple case, for when the data doesn’t ever | ||
change — but that’s no fun, so let’s add some mutability in the mix (we’ll also | ||
return to a single thread, just to keep things simple). | ||
|
||
Consider this code, which we’re going to attempt to draw a diagram for like | ||
above: | ||
|
||
```rs | ||
let mut data = 0; | ||
data = 1; | ||
data; | ||
data = 2; | ||
``` | ||
|
||
Working out executions of code like this is rather like solving a Sudoku puzzle: | ||
you must first lay out all the facts that you know, and then fill in the blanks | ||
with logical reasoning. The initial information we’ve been given is both the | ||
initial value of `data` and the sequential order of Thread 1; we also know that | ||
over its lifetime, `data` takes on a total of three different values that were | ||
caused by two different non-atomic writes. This allows us to start drawing out | ||
some boxes: | ||
|
||
```text | ||
Thread 1 data | ||
╭───────╮ ┌────┐ | ||
│ = 1 ├╌? │ 0 │ | ||
╰───╥───╯ ?╌┼╌╌╌╌┤ | ||
╭───⇓───╮ ?╌┼╌╌╌╌┤ | ||
│ data ├╌? │ ? │ | ||
╰───╥───╯ ?╌┼╌╌╌╌┤ | ||
╭───⇓───╮ ?╌┼╌╌╌╌┤ | ||
│ = 2 ├╌? │ ? │ | ||
╰───────╯ └────┘ | ||
``` | ||
|
||
Note the use of dashed padding in between the values of `data`’s column. Those | ||
spaces won’t ever contain a value, but they’re used to represent an | ||
unsynchronized (non-atomic) write — it is garbage data and attempting to read it | ||
would result in a data race. | ||
SabrinaJewson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
To solve this puzzle, we first need to bring in a new rule that governs all | ||
memory accesses to a particular location: | ||
> From the point at which the access occurs, find every other point that can be | ||
> reached by following the reverse direction of arrows, then for each one of | ||
> those, take a single step across every line that connects to the relevant | ||
> memory location. **It is not allowed for the access to read or write any value | ||
> that appears above any one of these points**. | ||
|
||
In our case, there are two potential executions: one, where the first write | ||
corresponds to the first value in `data`, and two, where the first write | ||
corresponds to the second value in `data`. Considering the second case for a | ||
moment, it would also force the second write to correspond to the first | ||
value in `data`. Therefore its diagram would look something like this: | ||
|
||
```text | ||
Thread 1 data | ||
╭───────╮ ┌────┐ | ||
│ = 1 ├╌╌┐ │ 0 │ | ||
╰───╥───╯ ┊ ┌╌╌┼╌╌╌╌┤ | ||
╭───⇓───╮ ┊ ├╌╌┼╌╌╌╌┤ | ||
│ data ├╌?┊ ┊ │ 2 │ | ||
╰───╥───╯ ├╌┼╌╌┼╌╌╌╌┤ | ||
╭───⇓───╮ └╌┼╌╌┼╌╌╌╌┤ | ||
│ = 2 ├╌╌╌╌┘ │ 1 │ | ||
╰───────╯ └────┘ | ||
``` | ||
|
||
However, that second line breaks the rule we just established! Following up the | ||
arrows from the third operation in Thread 1, we reach the first operation, and | ||
from there we can take a single step to reach the space in between the `2` and | ||
the `1`, which excludes the this access from writing any value above that point. | ||
|
||
So evidently, this execution is no good. We can therefore conclude that the only | ||
possible execution of this program is the other one, in which the `1` appears | ||
above the `2`: | ||
|
||
```text | ||
Thread 1 data | ||
╭───────╮ ┌────┐ | ||
│ = 1 ├╌╌┐ │ 0 │ | ||
╰───╥───╯ ├╌╌┼╌╌╌╌┤ | ||
╭───⇓───╮ └╌╌┼╌╌╌╌┤ | ||
│ data ├╌? │ 1 │ | ||
╰───╥───╯ ┌╌╌┼╌╌╌╌┤ | ||
╭───⇓───╮ ├╌╌┼╌╌╌╌┤ | ||
│ = 2 ├╌╌┘ │ 2 │ | ||
╰───────╯ └────┘ | ||
``` | ||
|
||
Now to sort out the read operation in the middle. We can use the same rule as | ||
before to trace up to the first write and rule out us reading either the `0` | ||
value or the garbage that exists between it and `1`, but how to we choose | ||
SabrinaJewson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
between the `1` and the `2`? Well, as it turns out there is a complement to the | ||
rule we already defined which gives us the exact answer we need: | ||
|
||
> From the point at which the access occurs, find every other point that can be | ||
> reached by following the _forward_ direction of arrows, then for each one of | ||
> those, take a single step across every line that connects to the relevant | ||
> memory location. **It is not allowed for the access to read or write any value | ||
> that appears below any one of these points**. | ||
|
||
Using this rule, we can follow the arrow downwards and then across and finally | ||
rule out `2` as well as the garbage before it. This leaves us with exactly _one_ | ||
value that the read operation can return, and exactly one possible execution | ||
guaranteed by the Abstract Machine: | ||
|
||
```text | ||
Thread 1 data | ||
╭───────╮ ┌────┐ | ||
│ = 1 ├╌╌┐ │ 0 │ | ||
╰───╥───╯ ├╌╌┼╌╌╌╌┤ | ||
╭───⇓───╮ └╌╌┼╌╌╌╌┤ | ||
│ data ├╌╌╌╌╌┤ 1 │ | ||
╰───╥───╯ ┌╌╌┼╌╌╌╌┤ | ||
╭───⇓───╮ ├╌╌┼╌╌╌╌┤ | ||
│ = 2 ├╌╌┘ │ 2 │ | ||
╰───────╯ └────┘ | ||
``` | ||
|
||
You might be thinking that all this has been is the longest, most convoluted | ||
explanation ever of the most basic intuitive semantics of programming — and | ||
you’d be absolutely right. But it’s essential to grasp these fundamentals, | ||
because once you have this model in mind, the extension into multiple threads | ||
and the complicated semantics of real atomics becomes completely natural. | ||
SabrinaJewson marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# Relaxed | ||
|
||
Now we’ve got single-threaded mutation semantics out of the way, we can try | ||
reintroducing a second thread. We’ll have one thread perform a write to the | ||
memory location, and a second thread read from it, like so: | ||
|
||
```rs | ||
// Initial state | ||
let mut state = 0; | ||
SabrinaJewson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// Thread 1: | ||
data = 1; | ||
// Thread 2: | ||
data; | ||
SabrinaJewson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
``` | ||
|
||
Of course, any Rust programmer will immediately tell you that this code doesn’t | ||
compile, and indeed it definitely does not, and for good reason. But suspend | ||
your disbelief for a moment, and imagine what would happen if it did. Let’s draw | ||
a diagram, leaving out the reading lines for now: | ||
|
||
```text | ||
Thread 1 data Thread 2 | ||
╭───────╮ ┌────┐ ╭───────╮ | ||
│ = 1 ├╌┐ │ 0 │ ?╌┤ data │ | ||
╰───────╯ ├╌┼╌╌╌╌┤ ╰───────╯ | ||
└╌┼╌╌╌╌┤ | ||
│ 1 │ | ||
└────┘ | ||
``` | ||
|
||
Let’s try to figure out where the line in Thread 2’s access joins up. The rules | ||
from before don’t help us much unfortunately since there are no arrows | ||
connecting that operation to anything, so we can’t immediately rule anything | ||
out. As a result, we end up facing a situation we haven’t faced before: there is | ||
_more than one_ potential value for Thread 2 to read. | ||
|
||
And this is where we encounter the big limitation with unsynchronized data | ||
accesses: the price we pay for their speed and optimization capability is that | ||
this situation is considered **Undefined Behavior**. For an unsynchronized read | ||
to be acceptable, there has to be _exactly one_ potential value for it to read, | ||
and when there are multiple like in this situation it is considered a data race. | ||
|
||
## “Out-of-thin-air” values |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# SeqCst |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# Signals | ||
|
||
(and compiler fences) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.