Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

locking - Linux Kernel Preemption during spin_lock and mutex_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. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...