Skip to content

Comment on Correctly implementing a spinlock in Modern C++

Comments

Correctly using a spinlock: Never when preemption is enabled

Therefore, also never when hold times and/or contention are non-trivial (i.e. obviating the PAUSE addition).

That one isn't actually as strict. Just because you used a spinlock doesn't mean you cause pathological degradation.

spinlocks in systems with preemption are only allowed if the scheduler knows about them, though. Otherwise a throughput-optimizing scheduler may cause hold times in the range of seconds, by keeping an aquiring thead active with the holding thread asleep. Such a scheduler wouldn't be suitable for interactive workloads, but for non-networked batch tasks it should be quite efficient (due to a combination of calling the scheduling logic less often (thus wasting less time on it), and less cache contention with the application.

In interrupt handlers and such you may need to use spin locks, as you can't sleep either way. The rule about preemption still applies though, and aside from fairness issues, will take care of preventing pathological hold times.

Yes that's right!

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.