2

我写了一个类似这样的代码:

它在非中断上下文中:

spin_lock_irqsave(&lock, flags);
printk("some message blah...\n");
spin_unlock_irqrestore(&lock, flags);

我正在运行此代码并且“看起来”很安全,因为我没有看到任何崩溃。但是,我不确定这是否真的是一个安全的代码。因为这可能会以 1/100000 的概率触发系统崩溃。

此外,我想知道在 spin_lock_irqsave 中调用“sleep”函数是否安全(在非中断上下文中)。

4

1 回答 1

4

内核代码在持有自旋锁时不应休眠。在Linux Device Drivers, Third Edition中,第 5 章的“自旋锁和原子上下文”部分指出:

Therefore, the core rule that applies to spinlocks is that any code must,
while holding a spinlock, be atomic. It cannot sleep; in fact, it cannot
relinquish the processor for any reason except to service interrupts (and
sometimes not even then).

至于printk,我相信在关键部分调用是安全的。源代码中的注释甚至提到:

This is printk(). It can be called from any context. We want it to work.
于 2014-12-18T17:43:36.950 回答