Ideas and Inspiration
local graph
Chapter 10 — Ideas and Inspiration
Section titled “Chapter 10 — Ideas and Inspiration”CHAPTER 10 Ideas and Inspiration
There are an infinite number of concurrency related topics, algorithms, data structures, anecdotes, and other potential chapters that could be part of this book. However, we’ve arrived at the final chapter and it’s almost time for us to part ways, hopefully leaving you with an excited feeling of new possibilities and ready to apply new knowledge and skills in practice.
This final chapter’s purpose is to provide inspiration for your own creations and future work by showing you some ideas that you can study, explore, and build on your own.
Semaphore
A semaphore is effectively just a counter with two operations: signal (also called up or V) and wait (also called down or P). The signal operation increments the counter up to a certain maximum, while a wait operation decrements the counter. If the counter is zero, a wait operation will block and wait for a matching signal operation, preventing the counter from ever becoming negative. It is a flexible tool that can be used to implement other synchronization primitives.
A semaphore can be implemented as a combination of a Mutex
A semaphore with a maximum value of one is sometimes called a binary semaphore, and can be used as a building block with which to build other primitives. For example, it can be used as a mutex by initializing the counter at one, using the wait operation for locking, and the signal operation for unlocking. By initializing it at zero, it can also be used for signaling, like a condition variable. For example, the standard park() and unpark() functions in std::thread can be implemented as wait and signal operations on a binary semaphore associated with the thread.
Note how a mutex can be implemented using a semaphore, while a semaphore can be implemented using a mutex (and a condition variable). It’s advisable to avoid using a mutex-based semaphore to implement a semaphore-based mutex, and the other way around.
Further reading:
- Wikipedia article on semaphores (https://oreil.ly/_rSRZ)
- Stanford University course notes on semaphores (https://oreil.ly/ZVaei)
If you want to allow multiple threads to (mostly) read and (sometimes) mutate some data, you can use an RwLock. When this data is just a single integer, you can use an atomic variable (such as AtomicU32) to avoid locking, which is more efficient. However, for larger chunks of data, like a struct with many fields, there’s no available atomic type that allows for lock-free atomic operations on the entire object.
Just like every other problem in computer science, this problem can be solved by adding a layer of indirection. Instead of the struct itself, you can use an atomic variable to store a pointer to it. This still doesn’t allow you to modify the struct as a whole atomically, but it does allow you to replace the entire struct atomically, which is nearly as good.
This pattern is often called RCU, which stands for “read, copy, update,” the steps necessary to replace the data. After reading the pointer, the struct can be copied into a new allocation that can be modified without worrying about other threads. When ready, the atomic pointer can be updated using a compare-and-exchange operation (“Compare-and-Exchange Operations” on page 42), which will only succeed if no other thread has replaced the data in the meantime.
The most interesting part about the RCU pattern is the last step, which does not have a letter in the acronym: deallocating the old data. After a successful update, other threads might still be reading the old copy, if they read the pointer before the update. You’ll have to wait for all those threads to be done before the old copy can be deallocated.
There are many possible solutions for this issue, including reference counting (like Arc), leaking memory (ignoring the problem), garbage collection, hazard pointers (a way for threads to tell the others what pointers they are currently using), and quiescent state tracking (waiting for each thread to reach a point at which it is definitely not using any pointers). The last one can be extremely efficient in certain conditions.
Many data structures in the Linux kernel are RCU based, and there are many interesting talks and articles about their implementation details that can provide a great deal of inspiration.
Further reading:
- Wikipedia article on the read-copy-update pattern (https://oreil.ly/egIIi)
- LWN article “What is RCU, Fundamentally?” (https://oreil.ly/GQZ6r)
Lock-Free Linked List
Section titled “Lock-Free Linked List”Expanding on the basic RCU pattern, you can add an atomic pointer to the struct to point to the next one, to turn it into a linked list. This allows for threads to atomically add or remove elements on this list, without having to copy the entire list for every update.
To insert a new element at the start of the list, you only have to allocate that element and point its pointer at the first element in the list, and then atomically update the initial pointer to point to your newly allocated element.
flowchart TD
A[AtomicPtr] --> B[Queue]
B --> C[next]
C --> D[next]
D --> E[(null)]
C --> F[Thread]
D --> G[Thread]
E --> H[Thread]
A --> I[Mutex locked]
A --> J[Queue locked]
There are many variations possible. The queue could be protected by its own lock bit or it could be implemented as a (partially) lock-free structure. The elements don’t have to be allocated on the heap, but could be local variables of the threads that are waiting. The queue could be a doubly-linked list with not only pointers to the next element, but also to the previous element. The first element could also include a pointer to the last element to allow efficiently appending an element at the end.
This pattern allows for implementing efficient locking primitives using only something that can be used to block and wake up a single thread, such as thread parking.
Windows SRW locks (“Slim reader-writer locks” on page 176) are implemented using this pattern.
Further reading:
- Notes on the implementation of Windows SRW locks (https://oreil.ly/El8GA)
- A Rust implementation of queue-based locks (https://oreil.ly/aFyg1)
Parking Lot–Based Locks
To make a highly efficient mutex that’s as small as possible, you can build upon the queue-based locks idea by moving the queue into a global data structure, leaving only one or two bits inside the mutex itself. This way, the mutex only needs to be a single byte. You could even put it in some unused bits of a pointer, allowing for very fine-grained locking at almost no extra cost.
The global data structure can be a HashMap that maps memory addresses to a queue of threads waiting on the mutex at that address. This global data structure is often called a parking lot, since it’s a collection of parked threads.
The pattern can be generalized by not only tracking queues for mutexes, but also for condition variables and other primitives. By tracking a queue for any atomic variable, this effectively provides a way to implement futex-like functionality on platforms that don’t natively support that.
This pattern is most well known from its 2015 implementation in WebKit, where it was used for locking JavaScript objects. Its implementation inspired other implementations, such as the popular parking_lot Rust crate.
Further reading:
- WebKit blog post, “Locking in WebKit” (https://oreil.ly/6dPim)
- Documentation of the parking_lot crate (https://oreil.ly/UPcXu)
Sequence Lock
A sequence lock is another solution to the problem of atomically updating (larger) data without using traditional (blocking) locks. It uses an atomic counter that is odd while the data is being updated, and even when the data is ready to be read.
The writing thread will have to increment the counter from even to odd before mutating the data, after which it has to increment the counter again to leave it at a (different) even value.
Any reading thread can, at any point and without blocking, read the data by reading the counter both before and after. If the two values from the counter are equal and even, there was no concurrent mutation, meaning you read a valid copy of the data. Otherwise, you might have read data that was concurrently being modified, in which case you should just try again.
This is a great pattern for making data available to other threads, without the possibility of the reading threads blocking the writing thread. It is often used in operating systems kernels and many embedded systems. Since the readers need only read access to the memory and no pointers are involved, this can be a great data structure to safely use in shared memory, between processes, without needing to trust the readers. For example, the Linux kernel uses this pattern to very efficiently provide timestamps to processes by providing them with read-only access to (shared) memory.
An interesting question is how this fits into the memory model. Concurrent non-atomic reads and writes to the same data result in undefined behavior, even if the read data is ignored. This means that, technically speaking, both reading and writing the data should be done using only atomic operations, even though the entire read or write does not have to be a single atomic operation.
Further reading:
- Wikipedia article on Linux’s Seqlock (https://oreil.ly/T28bW)
- Rust RFC 3301, AtomicPerByte (https://oreil.ly/Qavc7)
- Documentation of the seqlock crate (https://oreil.ly/yHd_7)
Teaching Materials
It can be great fun to spend many hours—or years—inventing new concurrent data structures and designing ergonomic Rust implementations of them. If you’re looking for something else to do with your knowledge on Rust, atomics, locks, concurrent data structures, and concurrency in general, it can also be very fulfilling to create new teaching materials to share your knowledge with others.
A
AArch64 (see ARM64) ABA problem, 44 aborting the process, 42 AcqRel, 57 (see also release and acquire memory ordering) acquire memory ordering (see release and acquire memory ordering) add instruction (ARM), 131 add instruction (x86), 131 address-based waiting (Windows), 177 (see also futex) air, out of thin, 56 alignment, 148 allocating IDs (see ID allocation) AMD processors, 127 and instruction (x86), 135 Arc, 9 building our own, 105-125 cyclic structures, 111 get_mut, 110 memory ordering, 108, 110, 123, 124 naming clones, 10 using for channel state, 95 weak pointers, 111 performance cost, 118 arguments, consuming, 94 ARM64 (processor architecture), 128 aarch64-unknown-linux-musl target, 130 other-multi-copy atomic, 151 weakly ordered, 153-155 ARM64 instructions add, 131
ARMv8.1 atomic instructions, 139, 155 b.ne (branch if not equal), 140 cbnz (compare and branch on nonzero), 138 clrex (clear exclusive), 138 cmp (compare), 140 dmb (data memory barrier), 158 ldar (load-acquire register), 154 ldaxr (load-acquire exclusive register), 154 ldr (load register), 131 ldxr (load exclusive register), 138 load-linked and store-conditional instructions, 138 mov (move), 140 overview, 159 ret (return), 131 stlr (store-release register), 154 stlxr (store-release exclusive register), 154 str (store register), 131 stxr (store exclusive register), 138 ARMv8 (see ARM64) ARMv8.1 atomic instructions, 139, 155 overview, 159 array::from_fn, 70 assembler, 128 assembly, 128 inspecting compiler output, 130 atomic, 31-47 compare-and-exchange operations, 42-46 caching, effect on, 146 compiler optimization, 140 example, ID allocation, 44 example, lazy initialization, 45, 62-64 memory ordering, 61 using for channel state, 93 using for mutex state, 187 using for reader-writer lock state, 205 using on AtomicPtr, 63 using to lock reference counter, 122 weak, 44 fetch-and-modify operations, 36-42 example, ID allocation, 41-42 example, progress reporting, 38-39 example, statistics, 39-40 wrapping behavior (add and sub), 37 (see also overflows) load and store operations, 32-36 compared to non-atomic operations, 51, example, lazy initialization, 35 example, progress reporting, 33-35 example, stop flag, 32-38 memory ordering (see memory ordering) reference counting (see Arc) atomic barriers (see fences) atomic fences (see fences) atomic types, 15, 31 compare_exchange, 43 compare_exchange_weak, 44 fetch_add, 37 wrapping behavior, 37 (see also overflows) fetch_and, 37 fetch_max, 37 fetch_min, 37 fetch_nand, 37 fetch_or, 37 fetch_store (see swap) fetch_sub, 37 wrapping behavior, 37 (see also overflows) fetch_update, 45 fetch_xor, 37 get_mut, 92 load, 32 store, 32 swap, 37 Atomic, 31 atomic-wait crate, 182 AtomicBool, 31 (see also atomic types) locking using, 60, 76 AtomicI8 (see atomic types) AtomicI16 (see atomic types) AtomicI32 (see atomic types) AtomicI64 (see atomic types) AtomicIsize (see atomic types) AtomicPtr, 31 (see also atomic types) compare-and-exchange, 63 lazy initialization, 63 AtomicU8 (see atomic types) AtomicU16 (see atomic types) AtomicU32 (see atomic types) AtomicU64 (see atomic types) AtomicUsize (see atomic types) auto traits, 16 b bne (branch if not equal) instruction (ARM), barriers (see fences) basics, 1 29 benchmarking, 104, 191 192 black_box, avoiding optimizations with, 104, 191 binary semaphore, 214 black_box, 104, 191 blocking, 161 channel, 101 103 condition variables, 26 futex wait operation, 167 (see also futex) mutexes, 18 Once and OnceLock, 36, 46 semaphores, 213 spin loop, 76 thread parking (see thread parking) boolean (atomic) (see AtomicBool) borrowing, 11 bending the rules, 15 error, 6 exclusive, 13 from multiple threads (Sync), 16 immutable, 11 (see also shared) local variables in a thread, 5 mutable, 11 (see also exclusive) shared, 13 splitting, 99 undefined behavior, 13
Box from_raw, 63, 108 into_raw, 63 leak, 8, 106 unmovable type, wrapping in, 165 btc (bit test and complement) instruction (x86), 135 btr (bit test and reset) instruction (x86), 135 bts (bit test and set) instruction (x86), 135 building our own Arc, 105-125 channels, 85-104 condition variables, 193-202 mutexes, 183-192 reader writer locks, 203-211 spin locks, 75-83 busy looping, 75 (see also spinning)
C standard library, 161 (see also libc) cache coherence, 142-144 protocol, 142 MESI, 143 MESIF, 143 MOESI, 143 write through, 142 cache lines, 142 performance experiment, 147-148 cache miss, 143 caching (processors), 141-148 (see also cache coherence) compare-and-exchange operations, effect of, 146 per core, 142 performance experiment, 144-148 cargo show-asm, 130 cas (compare and swap) instruction (ARM), 139 casa (compare and swap, acquire) instruction (ARM), 155 casal (compare and swap, acquire and release) instruction (ARM), 155 casl (compare and swap, release) instruction (ARM), 155 cbnz (compare and branch on nonzero) instruction (ARM), 138 Cell, 14
unsafe (see UnsafeCell) channels blocking, 101-103 borrowing, 98 building our own, 85-104 dropping, 89 one-shot, 87 safe interface, 90 Sender and Receiver types, 94, 98 storing in Arc, 95 avoiding, 98 unsafe interface, 88 Clone trait, 8, 10, 96, 107, 114 closures captured values moving, 4 naming, 10 spawning scoped threads using, 6 spawning threads using, 4 clrex (clear exclusive) instruction (ARM), 138 cmp (compare) instruction (ARM), 140 cmpxchg (compare and exchange) instruction (x86), 135-136 cmpxchg (compare-and-exchange) instruction (x86) #[cold], 190 compare-and-exchange operations (atomic), 42-46 on ARM64, 139-141 caching, effect on, 146 compiler optimization, 140 example, ID allocation, 44 example, lazy initialization, 45, 62-64 memory ordering, 61 using for channel state, 93 using for mutex state, 187 using for reader-writer lock state, 205 using on AtomicPtr, 63 using to lock reference counter, 122 weak, 44 on ARM64, 140 on x86-64, 135-136 Compiler Explorer, 130 compiler fence, 70, 156 compiler optimization black_box, avoiding with, 144, 191 #[cold], 190 of compare-and-exchange loops, 140 enabling, 130, 144 Index
#inline], 190 reordering, 49 complex instruction set computer (CISC), 131 concurrency; basics, 1-29 condition variables, 26-28 building our own, 193-202 example, 27 memory ordering, 195 pthread_cond_t, 164 thundering herd problem, 202 timeout, 28 using to build a channel, 85-87 Windows, 177 Condvar, 26 (see also condition variables) consume memory ordering, 65 consuming arguments by value, 94 contention (mutexes), 187, 189 benchmarking, 192 Copy trait, 89, 89 atomic types, not implementing, 39 moving, 8 critical section (Windows), 176 current thread, 2, 5, 24 cyclic structures (Arc), 111
D data races, 11 avoiding using atomics, 31, 51 Deref trait, 23, 81, 107 DerefMut trait, 19, 23, 81, 110 disassembler, 128, 130 dmb (data memory barrier) instruction (ARM), 158 rop function, 20, 82, 115 up trait, 19, 81, 82, 89, 92, 97, 108, 109, 114, 15, 121, 185 ord, 131
—emit=asm (rustc), 130 exclusive references, 13
F fair locks, 175 false sharing, 147 fences, 67-71, 108, 123 on ARM64, 158
compiler fence, 70, 156 instructions, 158-159 process-wide memory barriers, 70 on x86-64, 158 fetch-and-modify operations (atomic), 36-42
on ARM64, 137-139 example, ID allocation, 41-42 example, progress reporting, 38-39 example, statistics, 39-40 wrapping behavior (add and sub), 37 (see also overflows) on x86-64, 134-135fetch_store operation (atomic) (see swap operation) fetch_update (atomic), 45 FlushProcessWriteBuffers (Windows), 70 forgetting (see leaking) FreeBSD, umtx_op syscall, 173 (see also futex) from_fn (array), 70 futex, 166-174 cross-platform futex-like functionality, 181 example, 168 memory safety, 185 on other platforms, 173 operations (Linux), 169-174 FUTEX_CLOCK_REALTIME, 170 FUTEX_CMP_REQUEUE, 172 FUTEX_PRIVATE_FLAG, 173 FUTEX_REQUEUE, 171 FUTEX_WAIT, 169 futex_waitv syscall, 173 FUTEX_WAIT_BITSET, 170 FUTEX_WAKE, 170 FUTEX_WAKE_BITSET, 171 FUTEX_WAKE_OP, 172 priority inheritance, 173 requeuing, 171, 202 spurious wake-ups, 168 timeout, 169, 197 wait operation, 167 wake operation, 167
G globally consistent order, 66 (see also sequentially consistent memory ordering) Godbolt, 130 good luck, 220
guards dropping, 20 join guard, 7 mutex guard, 19, 183 read guard, 23, 203 spin lock guard, 80 write guard, 23, 203
H hand, things getting out of, 103 happens-before relationships, 51-54 in Arc, 108, 110 between threads, 52 locking and unlocking, 60, 77 spawning and joining threads, 53 through a release-acquire pair, 57, 59 chaining, 60 within the same thread, 52 hint::black_box, 144, 191 hint::spin_loop, 76
I ID allocation using compare_exchange_weak, 44 using fetch_add, 41-42 using fetch_update, 45 ideas and inspiration, 213-220 if let statement lifetime of temporaries, 22 ignorance, blissful, 56 immutable references, 11 (see also shared references) indivisible, 31 #[inline], 190 inspiration, 213-220 Instant, 40 instruction reordering (see reordering) instructions, 128-141 (see also ARM64 instructions; x86-64 instructions) compare-and-exchange operations, 135-136, 139-141 fences, 158-159 load and store operations, 132-133 load-linked/store-conditional (LL/SC) instructions, 137-137 memory ordering, 150-159 overview, 159 read-modify-write operations, 133-139
Intel processors, 127 interior mutability, 13-16, 78, 112 invalidation queues, 149
J jne (jump if not equal) instruction (x86), 136 join method, 3 JoinGuard, 7 JoinHandle, 3 joining threads, 3 happens-before relationship, 53
K kernel, 1, 161 interfacing with, 161-162 kernel-managed objects (Windows), 175
L L1/L2/L3/L4 cache, 142 label (assembly), 129 lazy initialization using compare_exchange, 45 using compare_exchange and allocation, 62-64 using load and store, 35 ldadd (load and add) instruction (ARM), 139 ldadda (load and add, acquire) instruction (ARM), 155 ldaddal (load and add, acquire and release) instruction (ARM), 155 ldaddl (load and add, release) instruction (ARM), 155 ldar (load-acquire register) instruction (ARM), ldaxr (load-acquire exclusive register) instruc- tion (ARM), 154 ldr (load register) instruction (ARM), 131 ldxr (load exclusive register) instruction (ARM), 138 leaking, 7, 8 by mistake, 89 a MutexGuard, 166 “Leakpocalypse”, 7 libc, 161 pthreads functionality in, 163 libpthread, 163 (see also pthreads) lifetime elision, 79, 100 in a struct, 80 of mutex guard, 21 specifying using plain English, 79 static, 4 linked list, 215 Linux
futex syscall, 167-174 (see also futex) arguments, 169 futex_waitv syscall, 173 interfacing with the kernel, 162 libc, role of, 162 membarrier syscall, 70 process-wide memory barrier, 70 RCU, 215load and store operations (atomic), 32-36 on ARM64 and x86-64, 132-133 compared to non-atomic operations, 51, 132 example, lazy initialization, 35 example, progress reporting, 33-35 example, stop flag, 32-33 load-linked/store-conditional (LL/SC) loop, 137-137 on ARM64, 137-138 compiler optimization, 140 lock poisoning, 21 lock prefix (x86), 134-135 lock_api crate, 186 luck, good, 220
M machine code, 128 machine instructions (see instructions) macOS futex-like functionality on, 181 interfacing with the kernel, 162, 174 os_unfair_lock, 175 main thread, 2 ManuallyDrop, 119 MaybeUninit, 87, 88, 89 mem::forget, 7 membarrier syscall, 70 memory barriers (see fences) memory fences (see fences) memory model, 51 memory ordering, 32, 49-73 on ARM64, 153-155 compiler fence, 70, 156
consume, 65 experiment, using relaxed instead of release and acquire, 155-157 fences, 67-71, 108, 123 happens-before relationship, 51-54, 57 Miri, detecting problems with, 110 misconceptions about, 71-73 out-of-thin-air values, 56 at processor level, 150-159 reference counting, 107, 108, 110, 123, 124 relaxed, 32, 54-56 (see also relaxed memory ordering) release and acquire, 57-64
(see also release and acquire memory ordering)locking and unlocking, 77 sequentially consistent, 66
(see also sequentially consistent memory ordering)specifying using plain English, 50 total modification order, 54, 59, 90, 91 on x86-64, 151-153 MESI cache coherence protocol, 143 MESIF cache coherence protocol, 143 mfence (memory fence) instruction (x86), 158 microinstructions, 134 Miri, 110 MOESI cache coherence protocol, 143 mov (move) instruction (ARM), 140 mov (move) instruction (x86), 132 movable, not critical section (Windows), 176 Pin, 165 pthread types, 165 wrapping in Box, 165 move closure, 4 multi-copy atomicity, 151 mutability, interior (see interior mutability) mutable references, 11 (see also exclusive references) Mutex, 15, 18 (see also mutexes) mutexes, 18-23 building our own, 183-192 as container, 23 contention, 187, 189 example, 19 fair, 175 happens-before relationship, 60 into_inner, 19 lifetime of mutex guard, 21 memory ordering, 60 Mutex type in Rust, 18 os_unfair_lock (macOS), 175 in other languages, 23 poisoning, 21 pthread wrapping in Rust, 164 pthread_mutex_t, 163 recursive, 176 robust, 174 Send requirement, 23 spin locks, 75 (see also spin locks) spinning, 75, 189 using to build a channel, 85-87 MutexGuard, 19 dropping, 20 lifetime of, 21 mutual exclusion (see mutexes)
N name of a thread, 5 NetBSD, futex support, 173 (see also futex) NonNull, 106
O -O flag (rustc), 130, 144 Once and OnceLock, 36, 46 one-shot channels, 87 OpenBSD, limited futex support, 173 (see also futex) operating systems, 161
(see also Linux; macOS; Windows) libraries shipped with, 162 synchronization primitives, 162optimization (see compiler optimization) or instruction (x86), 135, 136 Ordering, 32, 50 (see also memory ordering) AcqRel, 57
(see also release and acquire memory ordering)Acquire, 57
(see also release and acquire memory ordering)Consume, 66
Relaxed, 32, 54 (see also relaxed memory ordering) Release, 57
(see also release and acquire memory ordering)SeqCst, 66
(see also sequentially consistent memory ordering)os_unfair_lock (macOS), 175 other-multi-copy atomicity, 151 out of order execution (see reordering) out-of-thin-air values, 56 output locking, 4 overflows (atomic), 41 (see also wrapping behavior) aborting on, 42 notification counter, 195 panicking on, 41 preventing (compare-and-exchange), 44 reference counter, 107 usize, big enough, 199 overview of atomic instructions, 159 ownership moving, 4, 94 sharing, 7 transferring to another thread (Send), 16
P panicking poisoned mutexes, 21 RefCell, borrowing, 14 thread name in panic messages, 5 using a Condvar with multiple mutexes, 28 when joining a thread, 3, 5 when spawning a thread, 5 parking (see thread parking) parking lot-based locks, 218 parking_lot crate, 218 PhantomData, 16, 102 Pin, 165 pipelining, 149 pointers
atomic (see AtomicPtr) neither Send nor Sync, 17 NonNull, 106poisoning, lock, 21 POSIX, 162 pthreads, 163-166 println, use of output locking, 4 priority inheritance, 174 priority inversion, 173 privacy (modules), 194 process-wide memory barriers, 70 processes, 1 processor architecture, 127
(see also ARM64; x86-64) strongly ordered, 151 weakly ordered, 153processor caching (see caching) processor instructions (see instructions) processor registers, 129 return value, 133 pthreads, 163-166 pthread_cond_t, 164, 201 pthread_mutex_t, 163 dropping while locked, 166 pthread_rwlock_t, 163 wrapping in Rust, 164
Q queue-based locks, 217
R racing, 36 Rc, 8 RCU (read, copy, update), 214, 215 reader-writer locks, 22-23 avoiding accidental spinning, 206 building our own, 203-211 pthread_rwlock_t, 163 Send requirement, 23 SRW locks (Windows), 176 Sync requirement, 23 writer starvation, 23, 208 recursive locking, 163, 176 reduced instruction set computer (RISC), 131 RefCell, 14 RwLock compared to, 23 reference counting, 8-10 (see also Arc) references
exclusive, 13 immuta ble, 11 (see also shared) mutable, 11 (see also exclusive) shared, 13 regist ers, 129return value, 133 relaxed memory ordering, 32, 52, 54-56 counter-intuitive results, 53 misconceptions about, 71, 72 out-of-thin-air values, 56 reference counting, 107 total modification order, 54, 59, 90, 91 release and acquire memory ordering, 57-64 acquire fence, 67, 69, 108, 110, 123 on ARM64, 153-155 example, lazy initialization, 62-64 experiment, using relaxed instead, 155-157 happens-before relationship, 57, 59 chaining, 60 locking and unlocking, 60, 77 reference counting, 108, 110, 123, 124 release fence, 67 on x86-64, 152 —release flag (cargo), 130, 144 reordering (instructions), 49-51, 149-150
memory ordering, 150#[repr(align)], 148requeuing waiting threads, 171, 202 ret (return) instruction (ARM), 131 ret (return) instruction (x86), 131 robust mutexes, 174 rustup, 130 RwLock, 15, 22 (see also reader-writer locks) RwLockReadGuard, 23 RwLockWriteGuard, 23
S safe interface, 80, 90, 91 safety requirements of unsafe functions, 13 scheduler, 161 scoped threads, 5-7 semaphores, 213 Send trait, 16, 86, 102 error, 18 implementing for Arc, 106 requirement by Mutex and RwLock, 23 SeqCst (see sequentially consistent memory ordering) sequence locks, 218 sequentially consistent memory ordering, 66 on ARM64, 154 fence, 70 misconceptions about, 72, 73
on x86-64, 153 shadowing, 10 shared ownership, 7-10 leaking, 8 reference counting, 8 statics, 7 shared references, 13 mutating atomics through, 31 slim reader-writer locks (Windows), 176, 217 spawning threads, 2 failing to, 5 happens-before relationship, 53 scoped, 5 spin locks building our own, 75-83 cache lines, effect of, 148 compare-and-exchange, (not) using, 147 experiment, using wrong memory ordering, 155-157 guard, 80 memory ordering, 77 spin loop hint, 76, 190 spinning, 75, 123, 161 avoiding accidental (reader-writer lock), 206 splitting (borrowing), 99 spurious wake-ups, 25, 168, 200 SRW locks (Windows), 176, 217 stack size, 5 starvation, 23, 208 static lifetime, 4 statics, 7 stlr (store-release register) instruction (ARM), 154 stlxr (store-release exclusive register) instruction (ARM), 154 stop flag, 32 store buffers, 149 store operations (atomic) (see load and store operations) store-conditional (see load-linked/store-conditional) str (store register) instruction (ARM), 131 stress, reducing, 91 strongly ordered architecture, 151 stxr (store exclusive register) instruction (ARM), 138 sub (subtract) instruction (x86), 135 swap operation (atomic), 37 locking using, 76
Sync trait. 16, 86 implementing for Arc, 106 implementing for channel, 88 implementing for mutex, 183 implementing for reader-writer lock, 203 implementing for spin lock, 78 requirement by RwLock, 23 syscalls, 161 avoiding, 186, 198 SYS_futex (Linux), 167
(see also futex) arguments, 169T —target (rustc), 130 teaching, 219 thin air, out of, 56 thread builder, 5 thread name, 5 Thread object, 101 id, 2 unpark, 24, 101 thread parking, 24-26, 92, 101, 167 spurious wake-ups, 25 timeout, 28 example, 34 thread safety, 9, 16-18
(see also Send and Sync traits) keeping objects on one thread, 102ThreadId, 2 threads, 1 joining, 3 panicking, 3, 5 returning a value, 4 scoped, 5-7 spawning, 2 thundering herd problem, 202 time travel, 12 timeout condition variables, 28 futex, 169, 197 thread parking, 28 example, 34 total modification order, 54, 59, 90, 91
U uncontended (mutexes), 187, 189 benchmarking, 191 undefined behavior, 12 borrowing, 13 data races, 11 Miri, detecting with, 110 time travel, 12 uninitialized memory, 87 Unix systems interfacing with the kernel, 162 libc, role of, 162 unmovable critical section (Windows), 176 Pin, 165 pthread types, 165 wrapping in Box, 165 unpark (Thread), 101 unparking (see thread parking) unsafe code, 12 unsafe functions, 13 unsafe trait implementation, 17 UnsafeCell, 16, 78, 112 get_mut, 92 unsound, 12
V VecDeque, 85
W waiting (see blocking) WaitOnAddress (Windows), 178 WakeByAddressAll (Windows), 178 WakeByAddressSingle (Windows), 178 Weak (see Arc; weak pointers) weakly ordered architecture, 153 experiment, using relaxed instead of release and acquire, 155-157 Windows, 175-178 condition variables, 177 critical section, 176 FlushProcessWriteBuffers, 70 interfacing with the kernel, 162 kernel-managed objects, 175 Native API, 175
process-wide memory barrier, 70 SRW locks, 176, 217 WaitOnAddress, 178 WakeByAddressAll, 178 WakeByAddressSingle, 178 Win32 API, 175 windows crate, 175 windows-sys crate, 175 wrapping behavior (fetch_add and fetch_sub), 37 (see also overflows (atomic)) wrapping unmovable object in Box, 165 write-through cache coherence protocol, 142 writer starvation, 23, 208
X x86-64 (processor architecture), 127 other-multi-copy atomic, 151 strongly ordered, 151-153 x86_64-unknown-linux-musl target, 130 x86-64 instructions add, 131 and, 135 btc (bit test and complement), 135 btr (bit test and reset), 135 bts (bit test and set), 135 cmpxchg (compare and exchange), 135-136 jne (jump if not equal), 136 lock prefix, 134-135 mfence (memory fence), 158 mov (move), 132 or, 135, 136 overview, 159 ret (return), 131 sub (subtract), 135 xadd (exchange and add), 135 xchg (exchange), 134, 153 xor, 135 xadd (exchange and add) instruction (x86), 135 xchg (exchange) instruction (x86), 134, 153 xor instruction (x86), 135
About the Author
Section titled “About the Author”Mara Bos maintains the Rust standard library and builds real-time control systems in Rust. As team lead of the Rust library team, she knows all the ins and outs of the language and the standard library. In addition, she has been working with concurrent real-time systems for years at the company she founded. Maintaining the most-used library in the Rust ecosystem and working daily on safety critical systems has given her the hands-on experience to both understand the theory and bring it to practice.
Colophon
Section titled “Colophon”The animal on the cover of Rust Atomics and Locks is a Kodiak bear (Ursus arctos middendorffi). This species of brown bear is endemic to the Kodiak Archipelago of Alaska. They have been isolated from other bears for roughly 12,000 years.
Kodiak bears are one of the largest bears in the world. A male can stand 10 feet tall on his hind legs and 5 feet tall on all four. Males can weigh up to 1,500 pounds while females are 20% to 30% smaller. They are larger than black bears, showcasing a more prominent shoulder hump, less prominent ears, and longer, straighter claws. While they are a type of brown bear, they cannot be easily identified by the color of their fur, which can range from dark brown to light blonde.
The Kodiak Archipelago hosts a pristine landscape for the bears. Its temperate forests are full of lush greenery that flourishes due to ample amounts of rain. Winters on the archipelago are long and cold, followed by mild summers. The bears take advantage of the climate by optimizing their diet for whatever is in season. During spring and early summer they feed on rapidly growing grasses. Berries are consumed during late summer and early fall. Salmon runs last from May through September, and the bears feast on Pacific salmon that spawn in nearby lakes and streams. They are easily adaptable and can be drawn to improperly stored garbage and food at human campsites and homes.
Kodiak bears were once actively hunted to protect livestock, but hunting is now regulated to keep the population thriving. As a result, Kodiak bears have a conservation status of Least Concern. Many of the animals on O’Reilly covers are endangered; all of them are important to the world.
The cover illustration is by Karen Montgomery, based on a black-and-white engraving from Zoology. The cover fonts are Gilroy Semibold and Guardian Sans. The text font is Adobe Minion Pro; the heading font is Adobe Myriad Condensed; and the code font is Dalton Maag’s Ubuntu Mono.