如果(在多核系统上)我希望一次只由一个内核运行一个内核模块函数,我应该使用什么?换句话说,避免两个核心同时运行相同的功能;也就是说,其中一个核心应该等待另一个内核完成该函数的运行。
穆特克斯?自旋锁?还有别的吗?
发布于 2013-08-10 17:47:45
您需要使用spinlock()的变体,即raw_spin_lock_irqsave()、raw_spin_lock_irqrestore() (https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/linux/spinlock.h#n188),而不是mutex(),因为它们是可睡觉的,因此它们可能会在其他CPU上醒来。spinlock将确保您的代码不会被其他内核执行。它在documented /spinlock.txt (https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/spinlocks.txt)的Linux内核树中已经有了很好的记录。
发布于 2013-08-10 18:48:32
既然rakib已经建议使用自旋锁,我将进一步解释如何使用它们。
在设置自旋锁之后,例如。
static DEFINE_SPINLOCK(your_lock);您可以简单地用spin_lock_irqsave/spin_lock_irqrestore包装函数的内容,例如:
static void function_to_protect()
{
unsigned int flags;
spin_lock_irqsave(&your_lock, flags);
/* function body here */
spin_lock_ireqrestore(&your_lock, flags);
}如果您确信您的锁不会被中断处理程序碰触,您可以选择使用更轻量级的函数spin_lock和spin_unlock,并省略标志变量。
参考资料:https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/spinlocks.txt
https://stackoverflow.com/questions/18163752
复制相似问题