为什么拥有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.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值