Rendered at 02:16:04 GMT+0000 (Coordinated Universal Time) with Cloudflare Workers.
pizlonator 2 hours ago [-]
Super dangerous to benchmark lock performance using microbenchmarks. If you have a tiny benchmark, then you're putting the CPU and memory into a very specific and unusual state (everything is quiet other than the lock itself).
The real world story for locks is usually that you're not rage-contending 100% of the time, but that you have some contention combined with CPUs doing some real work and some real memory accesses.
What I've found is that in those more real scenarios, the locks that perform best in microbenchmarks fall apart compared to completely different and unexpected algorithms.
tombert 5 hours ago [-]
I genuinely had not heard of anyone actually using a spinlock in production code until I started using LMAX Disruptor a few years ago.
I was always told that they were an anti-pattern, and I think that generally that is a pretty good rule of thumb, but I guess like most stuff in CS: there are always exceptions to "good rules of thumb".
I still haven't actually explicitly written a spinlock for anything in production, but Disruptor has shown me that there are cases for it.
kazinator 1 hours ago [-]
Before we had futexes in the Linux kernel, spinlocks were used to boostrap the implementation of everything else in the user space threading library.
If you have futexes you can try to grab a lock with an atomic operation and if that fails, go wait on the futex via system call, so there is no need to spin. Spinlocks then remain useful as an optimization, because there are situations in which it is cheaper to spin around a bunch of times until the thread on another processor gives up the lock, than to take a trip into the kernel.
You can also spin, but with a scheduler yield in the loop; we don't normally think of that as a spinlock. That's what you fall back on after spinning some number of times and failing to get the lock.
In the Linux kernel, spinlocks are the low level primitive. They are very efficient because unlike user space threading, they are not faced with guesswork about scheduling. They are "surgical".
bob1029 4 hours ago [-]
To be really pedantic, it's a spin wait, not a spin lock in disruptor. You are waiting for a sequence, not mutually excluding some resource. Many threads can watch the same volatile at the same time without blocking each other.
nly 3 hours ago [-]
If you have an application where your threads are pinned to dedicated cores, and those cores are all isolated from general OS scheduling, then it's the lowest latency means to synchronize arbitrary things between threads
Entering the kernel with a futex wait or wake under contention costs a couple of microseconds, whereas a spinlock will cost you double digit to low triple digit nanos depending on cores/sockets etc
> Note that even OS kernels can have this issue - imagine what happens in virtualized environments with overcommitted physical CPU's scheduled by a hypervisor as virtual CPU's? Yeah - exactly. Don't do that. Or at least be aware of it, and have some virtualization-aware paravirtualized spinlock so that you can tell the hypervisor that "hey, don't do that to me right now, I'm in a critical region".
I can't be the only one who learned this the hard way by cramming too many vCPUs onto too few physical cores and initially wondering where the high load and latencies came from.
markus_zhang 2 hours ago [-]
Thanks for sharing. Can someone tell me what does this paragraph mean?
> Use a lock where you tell the system that you're waiting for the lock, and where the unlocking thread will let you know when it's done, so that the scheduler can actually work with you, instead of (randomly) working against you.
I have “implemented” a sleep lock in xv6. Is it what he meant? What does the Linux scheduler “know” about it and will do differently? (Trying to figure out what does “work with you” mean)
Thanks in advance.
moregrist 1 hours ago [-]
In simplest terms: if you don’t tell the kernel that you’re waiting, the scheduler assumes you aren’t and will wake you up and let you spin, to the detriment of other threads that aren’t waiting.
If the OS knows that a thread is waiting for a lock, the scheduler will not bother to schedule it until the lock is available.
In general, it’s tempting when you’re bound by lock latency to skip the syscall overhead of sleeping. But a lot of the time that’s a code smell that there are other inefficiencies in the system and you should rethink how you’re scheduling work.
sedatk 5 hours ago [-]
It’s one of the secret ingredients to avoid a Big Kernel Lock™.
ignoramous 4 hours ago [-]
> had not heard of anyone actually using a spinlock in production code
Optimistically spinning for a bit before falling back to futex or equivalent is very different from a spinlock.
mathisfun123 4 hours ago [-]
not all architectures have atomic cas
loeg 3 hours ago [-]
Real architectures you'd run more than a single thread on? Such as?
tom_ 55 minutes ago [-]
Quad core ARMv8-A, e.g., Nintendo Switch.
dalvrosa 3 days ago [-]
Thanks for sharing! Happy to get feedback :)
Note that I don't recommend spinlock for most cases, only when there is a 1:1 mapping between threads and phsycal CPU cores, and only after measuring
loeg 3 hours ago [-]
Spinlocks are unsuitable for situations where you can be involuntarily context switched (the vast majority of userspace programs). Probably worth mentioning that.
gavinlilly 3 hours ago [-]
If contention is expected, would it be better to first perform a relaxed read before the exchange? For example:
auto lock() noexcept -> void {
auto backoff = 1;
do {
while (locked_.load(std::memory_order_relaxed)) {
for (auto i = 0; i < backoff; ++i) _mm_pause();
backoff = backoff < 64 ? backoff << 1 : 64;
}
} while (locked_.exchange(true, std::memory_order_acquire);
}
nly 3 hours ago [-]
If you're expecting heavy contention, and there's no risk of any of the threads being descheduled, then FIFO spinlocks are probably best.
In a FIFO threads register themselves into a linked list, and the thread calling unlock() directly wakes the next. It's possible to have e.g. 20 threads in this case all spinning on their own cache lines (their private node), rather than a shared one (the lock head).
This can be coherence protocol optimal.
A dumb test and set spinlock, or variant thereof, is going to degrade quickly as all the cores are spinning on the same cacheline causing a lot of coherence traffic between cores (transitions between shared, exclusive and modified states)
jeffbee 4 hours ago [-]
This would have different answers depending on if it ran on a machine with a more closely-shared cache, right? For example on an Intel efficiency core cluster where 4 cores share an L2.
The real world story for locks is usually that you're not rage-contending 100% of the time, but that you have some contention combined with CPUs doing some real work and some real memory accesses.
What I've found is that in those more real scenarios, the locks that perform best in microbenchmarks fall apart compared to completely different and unexpected algorithms.
I was always told that they were an anti-pattern, and I think that generally that is a pretty good rule of thumb, but I guess like most stuff in CS: there are always exceptions to "good rules of thumb".
I still haven't actually explicitly written a spinlock for anything in production, but Disruptor has shown me that there are cases for it.
If you have futexes you can try to grab a lock with an atomic operation and if that fails, go wait on the futex via system call, so there is no need to spin. Spinlocks then remain useful as an optimization, because there are situations in which it is cheaper to spin around a bunch of times until the thread on another processor gives up the lock, than to take a trip into the kernel.
You can also spin, but with a scheduler yield in the loop; we don't normally think of that as a spinlock. That's what you fall back on after spinning some number of times and failing to get the lock.
In the Linux kernel, spinlocks are the low level primitive. They are very efficient because unlike user space threading, they are not faced with guesswork about scheduling. They are "surgical".
Entering the kernel with a futex wait or wake under contention costs a couple of microseconds, whereas a spinlock will cost you double digit to low triple digit nanos depending on cores/sockets etc
I can't be the only one who learned this the hard way by cramming too many vCPUs onto too few physical cores and initially wondering where the high load and latencies came from.
> Use a lock where you tell the system that you're waiting for the lock, and where the unlocking thread will let you know when it's done, so that the scheduler can actually work with you, instead of (randomly) working against you.
I have “implemented” a sleep lock in xv6. Is it what he meant? What does the Linux scheduler “know” about it and will do differently? (Trying to figure out what does “work with you” mean)
Thanks in advance.
If the OS knows that a thread is waiting for a lock, the scheduler will not bother to schedule it until the lock is available.
In general, it’s tempting when you’re bound by lock latency to skip the syscall overhead of sleeping. But a lot of the time that’s a code smell that there are other inefficiencies in the system and you should rethink how you’re scheduling work.
Go stdlib sync.Mutex uses spins: https://victoriametrics.com/blog/go-sync-mutex / https://archive.vn/BIb7F
Note that I don't recommend spinlock for most cases, only when there is a 1:1 mapping between threads and phsycal CPU cores, and only after measuring
In a FIFO threads register themselves into a linked list, and the thread calling unlock() directly wakes the next. It's possible to have e.g. 20 threads in this case all spinning on their own cache lines (their private node), rather than a shared one (the lock head).
This can be coherence protocol optimal.
A dumb test and set spinlock, or variant thereof, is going to degrade quickly as all the cores are spinning on the same cacheline causing a lot of coherence traffic between cores (transitions between shared, exclusive and modified states)