NewsCrawler.org

Mutex poisoning is not for everyone

Mutex poisoning is not for everyone
Image: Reddit

The author argues that mutex poisoning[1] is the wrong default for most applications. A mutex[2] guards a critical section so that only one thread changes shared data at a time. In Rust, poisoning records when a thread panics while holding the lock, and later lock() calls return an error.

The author says poisoning adds a flag to every mutex, which can increase its size, and adds code to every lock, even though poisoning is rarely needed. In the author's assembly comparison, the version that unwraps the lock takes 147 lines, the version that ignores panics takes 68 lines, and a non-poisoning mutex in current nightly Rust builds takes 34 lines. Rust uses the futex2[3] system call on most platforms, which lets a thread wait for a contended mutex.

The author says most critical sections are short and have no invalid intermediate state, so poisoning solves a niche problem and not the general one. The author supports a separate wrapper with poisoning for the cases that need it, and says Rust's default should make the common case easy. The author also argues that poisoning hampers readability and encourages workarounds.

Read the original bertptrs.nlDiscussion

Discussion

Commenters mostly agree that a non-poisoning mutex is useful and could be added to std, but not all of them think it should be the default. One commenter prefers that a panic in one thread also panics the main thread, and others suggest avoiding mutexes altogether where possible.

Sources

Published: First seen: Читать по-русски

Open as a page