gpt4 book ai didi

kernel - 为什么linux在内核代码持有自旋锁后禁用内核抢占?

转载 作者:行者123 更新时间:2023-12-04 23:23:19 24 4
gpt4 key购买 nike

我是 Linux 新手,正在阅读 Rubini & Corbet 所著的 Linux 设备驱动程序。我对与 spinlocks 相关的一项声明感到困惑;这本书说

If a nonpreemptive uniprocessor system ever went into a spin on a lock, it would spin forever; no other thread would ever be able to obtain the CPU to release the lock. For this reason, spinlock operations on uniprocessor systems without preemption enabled are optimized to do nothing, with the exception of the ones that change the IRQ masking status.



书中进一步指出

The kernel preemption case is handled by the spinlock code itself. Any time kernel code holds a spinlock, preemption is disabled on the relevant processor. Even uniprocessor systems must disable preemption in this way to avoid race conditions.



问题:在单处理器系统上,如果内核代码(代表用户进程执行)持有自旋锁时内核抢占被禁用,那么另一个进程怎么可能有机会运行并因此尝试获取自旋锁?为什么每当内核代码持有自旋锁时,Linux 内核都会禁用内核抢占?

最佳答案

你的第一个问题的答案是你的第二个问题背后的推理。

内核获取的自旋锁可以通过关闭抢占来实现,因为这可以确保内核将在没有其他进程干扰的情况下完成其临界区。重点是在内核释放锁之前,另一个进程将无法运行。

没有理由必须以这种方式实现;这只是一种实现它的简单方法,可以防止任何进程在内核持有的锁上旋转。但是这个技巧只适用于内核已经获得锁的情况:用户进程不能关闭抢占,如果内核正在旋转(即它试图获取一个自旋锁但另一个进程已经拥有它)它最好离开抢占上!否则系统将挂起,因为内核正在等待一个不会被释放的锁,因为持有它的进程无法释放它。

内核获取自旋锁是一种特殊情况。如果用户级程序获得了自旋锁,则不会禁用抢占。

关于kernel - 为什么linux在内核代码持有自旋锁后禁用内核抢占?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18254713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com