为什么拥有spinlock的时候不可以sleep

参考:http://stackoverflow.com/questions/4752031/why-cant-you-sleep-while-holding-spinlock

首先看下,spin_lock的实现:

static inline void spin_lock(spinlock_t *lock)
{
	raw_spin_lock(&lock->rlock);
}

 

#define raw_spin_lock(lock)	_raw_spin_lock(lock)

void __lockfunc _raw_spin_lock(raw_spinlock_t *lock)
{
	__raw_spin_lock(lock);
}
static inline void __raw_spin_lock(raw_spinlock_t *lock)
{
	preempt_disable();
	spin_acquire(&lock->dep_map, 0, 0, _RET_IP_);
	LOCK_CONTENDED(lock, do_raw_spin_trylock, do_raw_spin_lock);
}


最终调用spin_lock的时候,我们发现它会去调用preempt_disable(),不让进程可以抢占
1
很多书上说spin_lock的时候,不可以sleep.
确切的说,应该说是你这个时候用是个非常不明智的选择。
2
sleep 意味着进程主动让出cpu的控制权,上下文切换到别的可以运行的进程,但是却没有释放spinlock
3
  假设进程A,首先获得spinlock,这个是时候A sleep 主动让出CPU。
  kernel 调度到进程B , 且B也试图去获取同样的spinlock , B会一直自旋 ,
  kernel 已经不可能再调度到A(不可抢占,B会一直拥有CPU,直到主动放弃),A 也就不可能去释放spinlock
  B 也会永远spin下去 , 呵呵,这个就相当于导致了一个死锁的发生。


1
It's not that you can't sleep while holding a spin lock. It is a very very bad idea to do that
2
assume that a process sleeps while holding a spilock. If the new process that is scheduled tries to acquire the same spinlock, it starts spinning for the lock to be available. Since the new process keeps spinning, it is not possible to schedule the first process and thus the lock is never released making the second process to spin for ever and we have a deadlock
3
Sleep() means a thread/process yields the control of the CPU and CONTEXT SWITCH to another, without releasing the spinlock, that's why it's wrong.

你可能感兴趣的:(sync)