spin_lock 和 mutex_lock 期间的 Linux 内核抢占 [英] Linux Kernel Preemption during spin_lock and mutex_lock

查看:42
本文介绍了spin_lock 和 mutex_lock 期间的 Linux 内核抢占的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当内核空间中的进程持有spin_lock时,由于以下任何一种情况,该进程不能被抢占:

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. 当进程的时间片耗尽时
  2. 当高优先级进程变得可运行时
  3. 发生中断时

然而,如果进程阻塞、休眠或显式调用schedule(),它可以让出处理器.我的理解正确吗?

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

当内核空间中的进程持有一个mutex_lock时,该进程是否可以因上述1、2、3条件被抢占.

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.

推荐答案

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

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.

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

  • 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.

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

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.

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

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.

这篇关于spin_lock 和 mutex_lock 期间的 Linux 内核抢占的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆