3 ms·
> The thing you're locking is often soon unlocked. If the holder of the lock got preempted you could be spinning for a very long time.
by ahupp 6y ago
> The thing you're locking is often soon unlocked.
If the holder of the lock got preempted you could be spinning for a very long time.
- titzer 6y agoThis is why spinlocks don't spin forever; they will break out of the spinloop and do a full-fledged OS-level lock acquisition, which will deschedule the thread.
- lokedhs 6y agoYou still have the problem if your spinlock gets preempted while spinning. You really should only use a spinlock if you can disable preemption, which is usually limited to the kernel or realtime processes.
- titzer 6y agoIt's no worse than being preempted anywhere else, as long as your spin sequence doesn't preclude other threads from acquiring that lock when it is released; in fact it is often better. If you are preempted while spinning to acquire a lock then that is working as intended (WAI), because you yield the CPU to runnable work, instead of burning it. > You really should only use a spinlock if you can disable preemption, which is usually limited to the kernel or realtime processes. Oh god, no, don't do that. Then you could livelock if you don't do a hybrid strategy, because you are totally hosed if all your cores enter the unpreemptable spin sequence. Maybe you are thinking of a different scenario, where the thread is preempted in the spinloop, but the kernel thinks it is runnable and at some future time just reschedules it, and it then continues to spin. That can happen, but the thread should break out of its spinloop and block anyway if the spinlock is tuned properly, so at most you just broke up the spinning across reschedules, and haven't fundamentally made anything worse. In an ideal world, if the kernel preempts a thread in a spinloop, it should transition it directly into the waiting state, and not reschedule it until it can acquire the lock. But since spinloops are in userspace, the kernel usually has no idea what is going on.