Skip to content
HN On Hacker News ↗

Mutex poisoning is not for everyone

▲ 12 points • 1 comments • by birdculture • 2d ago • HN discussion ↗

Pangram verdict · v3.3

We believe that this entire text is human-written.

0 %

AI likelihood · overall

Human
100% human-written 0% AI-generated
SEGMENTS · HUMAN 1 of 1
SEGMENTS · AI 0 of 1
WORD COUNT 1,709
PEAK AI % 0% · §1
Analyzed
Nov 24
backend: pangram/v3.3
Segments scanned
1 windows
avg 1709 words each
Distribution
100 / 0%
human / AI fraction
Verdict
Human
Pangram v3.3

Article text · 1,709 words · 1 segments analyzed

Human AI-generated
§1 Human · 0%

After some recent discussion on the topic of mutex poisoning and notably a blog post that I thought was interesting, thoughtful, exhaustive, yet completely disagreed with, I wanted to comment on the debate myself. To me, poisoning-by-default is one of biggest mistakes that were made in the language, next to some others that are a story for a different time. In short, I believe that Mutex poisoning is the wrong choice for most applications, as it significantly pessimises code performance in the general case in addition to hampering readability while encouraging bad code patterns to deal with its weirdness in order to solve a niche problem that doesn’t even solve the general problem. In theory, a mutex guards a critical section of the code. That code changes the state of a piece of data free from interference of concurrent threads, then releases the lock. That code might then encounter an error, and release the lock in the middle of doing its important work. For example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 fn important(always_even: Arc<Mutex<i32>>) -> i32 { // Invariant: always_even must always be even let mut handle = always_even.lock().unwrap(); *handle += 1; risky_operation(); *handle += 1; *handle } fn risky_operation() { if rng().next_u32() % 42 == 0 { panic!(); } } The following code will work fine most of the time, but if the dice roll doesn’t go our way, the always_even mutex gets unlocked in an invalid state. In Rust, today, poisoning exists to handle this. If a guard is released abnormally (while panicking), it records that this happened in a boolean. Any future calls to lock() will return Err(PoisonError), which will trigger a panic when we unwrap it. The bad state is never observed and all is well. You might have felt that the example I made up was somewhat contrived. That’s because it is. Real cases of this pattern can and do happen, but most of the use cases that involve mutexes are much simpler. Many critical sections are no longer than a variable assignment, or doesn’t have an invalid in-between state. There are cases in lower level programming where a mutex guards a piece of data that is not directly inside it, or is outside the view of the program entirely. In fact, I’ve written a wrapper for a C library that worked like that. Though I disagree with the notion that this is the common case. I do recommend anyone Rain’s blog on the matter, as she has some good examples of how you can cause violations of these critical sections (even without mutexes) and I wholeheartedly support the idea of a Poison wrapper for the use cases that need it. I suspect the domains she works on lend themselves more towards these issues compared to mine. Rust’s default behaviour should make the common case easy and the rare case possible. Side-note: how mutexes work This section is only tangentially related to the topic at hand, but I already wrote it and wasn’t ready to kill my darlings.1 Skip to the next section to continue the discussion on poisoning. In Rust, for most platforms, mutexes are implemented using the futex2 system call. It allows for operations to remain purely in user-space as long as the mutex in question isn’t contended, which is nice for performance reasons. Under the hood, a mutex is a simple 32-bit integer on most platforms even though it only holds three unique values: If it’s zero, the mutex is free and can be claimed by any thread by a simple atomic compare-exchange. If it’s one, the mutex is held but there are no waiting threads. This is useful to know, as it means there are no threads that we need to wake up when releasing the mutex, and we can yet again remain in userspace. If it’s two, the mutex is held and some other thread is waiting for it. This means some additional care should be taken when unlocking. Flow chart showing how a mutex acquisition is implemented in Rust, using atomic operations and futex primitives. Note how the uncontended case remains entirely in user-space and does not sleep the thread. Rust implements this with a few atomic operations and the futex_wait call. Crucially, the path for locking a mutex that isn’t contended is a single atomic operation. The only operation that requires a context switch is futex_wait. Unlocking is even simpler. The thread that holds the mutex first releases the lock, then optionally, if there was an indication that the lock was contended, wakes any sleeping threads so they can try to acquire the lock. Flow chart showing how a mutex release in Rust. First, we swap the current value with 0, and depending on whether it was originally 1 (simply locked) or 2 (contended), we optionally wake any sleeping threads. How poisoning harms every single piece of code As discussed in too much detail above, (un)locking mutexes is cheap as long as they’re not contended, and when contended, they are at least cheap instruction wise. This is where poisoning mutexes get you. In short, being able to poison is a cost that is always paid, but seldom used. To start, poisoning is essentially implemented by adding an AtomicBool field to every Mutex. Due to alignment, this grows the size of every mutex by anywhere from zero bytes to an additional pointer. This isn’t terrible but for use cases where you have many mutexes guarding small objects, this can add up. The real issue to me however is in code size. Let’s start with another contrived example, a function that reads its argument, copies it, and returns it. An idealised version of that would be the following. 1 2 3 pub fn get_contents(val: &i32) -> i32 { *val } This compiles down to 2 instructions and a label. Copy the data into the register then return. 1 2 3 example::check_contents::h197b180b47e24703: mov eax, dword ptr [rdi] ret Of course, this doesn’t work for any context that needs shared mutation, but we can consider it our baseline. Perfection would look like this. So, let’s ignore that atomic integers exist and add a mutex to this story. We will go over the generated assembly code for each, and you can compare the code in its entirety in this Compiler Explorer overview. Base case: Locking and unwrapping We can update the code above to actually use mutexes, and simply lock-then-unwrap the mutex. 1 2 3 4 5 use std::sync::Mutex; pub fn check_contents(mutex: &Mutex<i32>) -> i32 { *mutex.lock().unwrap() } This compiles to a total of 147 lines of assembly which I’m not going to reproduce here in full. 75 of those are specifically inlined to this particular function and cannot be reused. About 45 those are monomorphised3 for mutexes guarding an i32 The remainder is global program information and might be reused for other locks. To divide that up a different way, we have code checking the poison status code doing the mutex manipulation code to initiate a poison in case of a panic code for preparing to panic should we need to code for displaying a panic some dyn drop glue Most of this is inlined into the function. This in turn affects performance, as this limits how much of your “real” code fits in the CPU’s instruction cache. The laptop I’m writing this on has a paltry 32KiB of instruction cache. Luckily we can do better. Removing the panic Most of the code generated in the previous example had to do with setting up the panic, and checking the conditions. But we don’t care about panicking. We can simply acknowledge the PoisonError and continue. That looks as follows: 1 2 3 4 5 6 use std::sync::Mutex; use std::sync::PoisonError; pub fn check_contents(mutex: &Mutex<i32>) -> i32 { *mutex.lock().unwrap_or_else(PoisonError::into_inner) } This results in only 68 lines of assembly, which is much better, though all of it is inlined to our function. Compared to before, we’ve lost all panic related code. There’s still some unnecessary branching related to whether the mutex is poisoned, as well as a little dance to track poisoning in our function. Our function can never panic, but compiler optimisations currently do not remove the atomic loads and stores involved here. Nevertheless, if you want to target stable Rust and you don’t care about panics, this is what you should do at the moment. The ideal: no poison handling at all In the current nightly builds of Rust, there are non-poisoning mutexes that can don’t have any of the overhead. We can optimise our code from above to make use of them. 1 2 3 4 5 6 7 #![feature(nonpoison_mutex)] #![feature(sync_nonpoison)] use std::sync::nonpoison::Mutex; pub fn check_contents(mutex: &Mutex<i32>) -> i32 { *mutex.lock() } No unwrapping, and it only results in 34 lines of assembly code. This is short enough for me to walk through it. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 example[da70a55c1c00d324]::check_contents: push rbp push rbx push rax xor ebp, ebp mov ecx, 1 xor eax, eax lock cmpxchg dword ptr [rdi], ecx ; (1) check if mutex is held, and if not, claim it jne .contended ; (2) mutex was not zero, jump to contended case mov eax, dword ptr [rdi + 4] ; (4) if not, load the value xchg dword ptr [rdi], ebp ; (5) unlock the mutex cmp ebp, 2 ; (6) check if there are other threads waiting je .exit_with_threads_waiting .fast_exit: add rsp, 8 pop rbx pop rbp ret .contended: mov rbx, rdi call qword ptr [rip + <std[3ebc094a278a8d54]::sys::sync::mutex::futex::Mutex>::lock_contended@GOTPCREL] ; (3) Perform the spin/futex_wait loop mov rdi, rbx ; mov eax, dword ptr [rdi + 4] ; (4) load the value xchg dword ptr [rdi], ebp ; (5) unlock the mutex cmp ebp, 2 ; (6) check if there are other threads waiting jne .fast_exit .exit_with_threads_waiting: mov ebx, eax call qword ptr [rip + <std[3ebc094a278a8d54]::sys::sync::mutex::futex::Mutex>::wake@GOTPCREL] ; (7) wake sleeping threads mov eax, ebx add rsp, 8 pop rbx pop rbp ret I’ve added comments and labels to the assembly so the steps from the (un)locking flow charts become