加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-14 00:29:52 所属栏目:Linux 来源:网络整理
导读:我是 Linux的新手,正在阅读Rubini amp;的Linux设备驱动程序.科比特.我对一个与自旋锁相关的陈述感到困惑;这本书说明 If a nonpreemptive uniprocessor system ever went into a spin on a lock,it would spin forever; no other thread would ever be able t
我是 Linux的新手,正在阅读Rubini& amp;的Linux设备驱动程序.科比特.我对一个与自旋锁相关的陈述感到困惑;这本书说明

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内核会在内核代码持有自旋锁时禁用内核抢占?

解决方法

你的第一个问题的答案是你的第二个问题背后的原因.

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读