Why can't you sleep while holding spinlock?

前端 未结 8 2029
醉梦人生
醉梦人生 2020-12-08 12:17

In the linux kernel, why can\'t you sleep while holding a spinlock?

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 12:46

    The key point is in Linux kernel, acquiring a spin lock will disable preemption. Thus sleeping while holding a spin lock could potentially cause deadlock.

    For example, thread A acquires a spin lock. Thread A will not be preempted until it releases the lock. As long as thread A quickly does its job and releases the lock, there is no problem. But if thread A sleeps while holding the lock, thread B could be scheduled to run since the sleep function will invoke the scheduler. And thread B could acquire the same lock as well. Thread B also disables preemption and tries to acquire the lock. And a deadlock occurs. Thread B will never get the lock since thread A holds it, and thread A will never get to run since thread B disables preemption.

    And why disabling preemption in the first place? I guess it's because we don't want threads on other processors to wait too long.

提交回复
热议问题