Urgent.News

What's breaking now, across thousands of outlets.

Tech

Spinlocks Considered Harmful (2020)

In this post, the author expresses strong opinions about spinlocks, a synchronization primitive that they maintain the once_cell crate, which is not compatible with #[no_std]. They argue that spinlocks should not be used in #[no_std] environments due to their inefficiencies and potential for causing system-wide issues. The source material states that spinlocks are implemented entirely in user space, meaning that a "spinning" thread appears to the OS like a thread performing a heavy computation.

The author explains that using a system call like park_this_thread allows the OS to take a thread off the CPU until it is woken up by an unpark_some_thread call. However, they argue that this logic is flawed because a thread can be preempted at any time, leading to several unfortunate consequences. One consequence is priority inversion, where a low-priority thread enters a critical section while competing high-priority threads are unable to complete their critical sections due to repeated scheduling of other threads.

The author also discusses how this issue becomes even more problematic on bare metal systems, where there is no OS to preempt threads, but instead, the processor can be interrupted by peripheral devices, leading to guaranteed deadlocks if the main code is in the middle of a critical section when an interrupt arrives. The author demonstrates this pattern by using the getrandom crate, which uses spinning in the LazyUsize utility type.

They create a scenario where one thread has low priority and the rest have high priority, simulating a slow /dev/random file descriptor to trigger priority inversion. The source material provides a link to the implementation of this plan, showing how this disaster scenario can be easily reproduced.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at matklad.github.io →

More in Tech

More from Friday 9 October →