4 ms·
No, linux pessimizes for that case if you do not cooperate with the scheduler. You can implement spinlocks in userspace under specific circumstances. You will
by the8472 7y ago
No, linux pessimizes for that case if you do not cooperate with the scheduler.
You can implement spinlocks in userspace under specific circumstances. You will need to mark your threads as realtime threads[0] and have a fallback to futex if the fast path (spinning) doesn't work out. And even then you need to benchmark on multiple machines and with realistic workloads (not microbenchmarks) to see whether it's actually worth it for your application. It's complex, linus goes into more detail here[1]
[0] http://man7.org/linux/man-pages/man3/pthread_spin_init.3.html#NOTES http://man7.org/linux/man-pages/man3/pthread_spin_init.3.htm...
[1] https://www.realworldtech.com/forum/?threadid=189711&curpostid=189755 https://www.realworldtech.com/forum/?threadid=189711&curpost...
- shadowgovt 7y agoDo Windows, MacOS/iOS, and console OS's treat spinlocks more friendly than Linux?
- CoolGuySteve 7y agoIn Windows, CriticalSection can spin for a user-defined period of time, which is more or less what you want. Although it would probably make more sense for it to have a "spin until my quantum is over" option because how is the caller supposed to know that? https://docs.microsoft.com/en-us/cpp/cppcx/wrl/criticalsection-class?view=vs-2019#criticalsection https://docs.microsoft.com/en-us/cpp/cppcx/wrl/criticalsecti...
- quotemstr 7y agoIf you have a fallback to futex, then what you have isn't a spinlock, but an adaptive mutex (which spins, then blocks). Lots of operating systems have those already and you don't need to build your own.
- shaklee3 7y agoOr just use a futex alone, since that mimics its behavior enough.
- the8472 7y agoIf you really want to use a pure spinlock you'll either have to accept that worst-case behavior being worse than a mutex or you have to jump through a lot of hoops (pinning threads, isolating cores, reassigning interrupts) to make sure you don't get descheduled. Because the scheduler won't know anything about priority inversions or even waiting threads, they all look runnable.