spin_lock 和 mutex_lock 期间的 Linux 内核抢占

发布于 2024-11-17 22:33:40 字数 274 浏览 3 评论 0原文

当内核空间中的进程持有spin_lock时,由于以下任一情况,该进程将无法被抢占:

  1. 当进程的时间片耗尽
  2. 时 当高优先级进程变为可运行
  3. 时 当发生中断

但是,如果进程阻塞、休眠或显式调用 schedule(),则该进程可以让出处理器。我的理解正确吗?

当内核空间中的进程持有mutex_lock时,该进程是否会因上述1、2、3所列出的条件而被抢占。

When a process in the kernel space is holding a spin_lock, the process cannot be preempted due to any of the following conditions :

  1. When the time-slice of the process gets exhausted
  2. When a high priority process becomes runnable
  3. When an interrupt occurs

However the process can yield the processor if it blocks, sleeps, or explicitly call schedule(). Is my understanding correct?

When a process in the kernel space is holding a mutex_lock, can the process be preempted due to the above conditions listed as 1, 2 and 3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执笏见 2024-11-24 22:33:40

当前的自旋锁实现使用两种完全独立的机制来确保互斥,一种用于处理处理器间排除,另一种用于处理本地处理器线程和中断处理程序。

  • spin_lock 本身仅用于在两个或多个处理器内核之间提供互斥锁。任何遇到锁定的自旋锁的处理器基本上都会被卡住,直到另一个处理器释放它。自旋锁在单处理器系统上没有任何作用 - 除了增加完全死锁的机会 - 因此通常在内核编译时被删除。

  • 为了提供本地处理器互斥锁,spin_lock() 调用 preempt_disable()(在抢占式调度系统上)以防止在持有锁时任何其他线程运行;类似地,spin_lock_irqsave() 也执行与 local_irq_save() 相同的操作,以禁用中断以防止本地处理器上运行任何其他内容。

从上面可以明显看出,使用自旋锁可能会搞砸整个机器,因此自旋锁应该只在很短的时间内使用,并且在持有锁时永远不应该做任何可能导致重新安排的事情。

mutex_lock 的情况完全不同 - 只有尝试访问锁的线程才会受到影响,如果线程命中锁定的互斥锁,则会发生重新调度。因此,mutex_locks 不能在中断(或其他原子)上下文中使用。

Current implementations of spin locks use two entirely separate mechanisms to ensure mutual exclusion, one for dealing with inter-processor exclusion and one for dealing with the local processor threads and interrupt handlers.

  • There is the spin_lock itself which is only there to provide mutex between two or more processor cores. Any processor hitting a locked spin lock is basically stuck until another processor releases it. Spin locks serve no purpose on single processor systems - other than to increase the chance of total deadlock - so are usually removed at kernel compile time.

  • To provide local processor mutex, spin_lock() calls preempt_disable() (on pre-emptive scheduling systems) to prevent any other thread from running whilst the lock is held; similarly spin_lock_irqsave() also does the equivalent of local_irq_save() to disable interrupts to prevent anything else at all running on the local processor.

As should be obvious from the above, using spin locks can gum up the whole machine so spin locks should just be used for very short periods of time and you should never do anything that might cause a reschedule whilst holding a lock.

The case with mutex_lock is totally different - only threads attempting to access the lock are affected and if a thread hits a locked mutex then a reschedule will occur. For this reason mutex_locks cannot be used in interrupt (or other atomic) contexts.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文