spin_lock, spin_lock_irq and spin_lock_irqsave

spin lock

spin lock has three variants: spin_lock, spin_irq and spin_irqsave. I am not going to talk the internal details, but give the hard rule to choose which to use. spin lock is used to protect the short/quick critical section. A critical section could be in process context or in interrupt handler. The *_irq and *_irqsave ones are for cases when the contended data could be accessed from both process context and interrupt hander.

spin_lock_irqsave

If the data could be accessed from process context or interrupt context, usually you should use spin_lock_irqsave version like:

spinlock_t mr_lock = SPIN_LOCK_UNLOCKED;
unsigned long flags;
spin_lock_irqsave(&mr_lock, flags);
/* critical section ... */
spin_unlock_irqrestore(&mr_lock, flags);

The use of spin_lock_irqsave() will disable interrupts locally and provide the spinlock on SMP. This covers both interrupt and SMP concurrency issues. With a call to spin_unlock_irqrestore(), interrupts are restored to the state when the lock was acquired.

spin_lock_irq

Different with *_irqsave, spin_lock_irq will lock and unconditionally disables the IRQ, and spin_unlock_irq unlocks and re-enable the IRQ as below:

spinlock_t mr_lock = SPIN_LOCK_UNLOCKED;
spin_lock_irq(&mr_lock);
/* critical section ... */
spin_unlock_irq(&mr_lock);

The problem is that you may enable the IRQ unexpectedly when the IRQ was already disabled before spin_lock_irq.

spin_lock

Only when you are sure the data will only be accessed in process context, you're safe to use spin_lock without bothering with enabling/disabling the interrupt.

转载于:https://my.oschina.net/u/2475751/blog/1590416

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值