您的位置:首页 > 其它

spin_lock, spin_lock_irq and spin_lock_irqsave

2017-12-15 00:00 344 查看

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: