Linux spin lock and semaphore "turn"

Source: Internet
Author: User
Tags mutex semaphore

Transferred from: http://blog.csdn.net/xu_guo/article/details/6072823

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

A spin lock can only be held by an executable thread (except for read-write spin locks). The spin lock does not cause the caller to sleep, and if an execution thread attempts to obtain a spin lock that is already held, the thread will keep busy looping and waiting (CPU-intensive) to see if the spin lock's holder has released the lock and the word "spin" is named.

Since spin-lock users generally keep the lock time very short, it is necessary to choose a spin instead of sleep, and the spin lock is much more efficient than a mutex.

Semaphores and read and write semaphores are suitable for long periods of time, they cause the caller to sleep, and therefore can only be used in the context of the process (because the interrupted context does not allow hibernation) (the variant of _trylock can be used in the interrupt context), whereas a spin lock is suitable for a very short time. Because a competing spin lock causes the thread that requests it to spin when it waits to be re-usable, it is particularly wasteful of processing time, which is the key point of the spin lock, so the spin lock should not be held for a long time. In the actual application of the spin lock code only a few lines, and the time to hold the spin lock is generally not more than two times the upper and lower side of the switch, because once the thread to switch, at least the cost of cutting out to cut two times, the spin-lock takes longer than two context switches, we can let the thread sleep, which loses the meaning of

If the protected shared resource is accessed only in the context of the process, it is appropriate to use semaphores to protect the shared resource, and if the access time to the shared resource is very short, the spin lock can. However, a spin lock must be used if the protected shared resource needs to break context access, including the bottom half of the interrupt handling handle and the top half of the soft interrupt.

The spin lock retention period is a preemption failure (the kernel is not allowed to be preempted) , while the semaphore and read/write semaphore retention periods can be preempted. spin locks are only available if the kernel is preempted or SMP The case is only really needed in a single CPU and the non-preemptive kernel, all operations of the spin lock are empty operations.

(problem: In a single CPU can preempt the kernel, if a process requests a spin lock, then he always consumes CPU The loop waits for the spin lock to be available, so the process that originally occupied the spin lock is not using the CPU Opportunity, how to release its own occupied spin lock?

answer: This situation should not happen in practice. Because of the initial situation, a process requires a spin lock, and this time the spin lock is not occupied, so he locks and enters the critical section. Because this time the kernel has been set to a non-preemptive spin lock, so the running process will not be tuned to the CPU , so there will be no other process to request the already occupied spin lock, when the critical section code processing is complete, release the spin lock, At this time the kernel is also the spin lock is set to a preemptive mode, this time other processes can be scheduled, so you can request a spin lock and other operations. So the situation in question should not happen in practice.

Note that if the spin lock is requested in a critical section of a process that has been locked for a spin lock, the process spins there, causing the panic. )

An execution unit to access a shared resource protected by a spin lock, a lock must be obtained before the lock is released after the shared resource has been accessed. If no execution unit holds the lock when acquiring a spin lock, the lock is immediately obtained, and if the lock has a hold when the spin lock is acquired, then the acquire lock operation will spin there until the lock is released by the hold of the spin lock.

Whether it is a mutex or a spin lock, there can be at most one hold at any time, and it is said that at most one execution unit can acquire a lock at any time (except for read-write locks). The implementation of the spin lock is closely related to the architecture, and the code is generally implemented by the Assembly, defined in the file, and the actual interface defined in the folder.

Since spin locks are held at most by an execution thread at the same time, only one thread at a time can be in the critical section, which provides a protection mechanism for multiple processors to prevent concurrent access, but on a single processor, a spin lock is not added to the compilation. It is only used as a switch to set whether the kernel preemption mechanism is enabled ( GX 's own understanding: in a single-core preemptive kernel, the spin lock lock causes the preemption to be disabled, and the spin lock unlock causes the recovery preemption mode. )。 Note that the spin lock implemented by the Linux kernel is not recursive, unlike the spin lock implementation in other operating systems, if you want a lock you are holding, you must spin and wait for yourself to release the lock, but you are in a spin-busy wait, so you never have a chance to release the lock, so you Be locked up by yourself, be sure to pay attention!

A spin lock can be used in an interrupt handler, but it is important to prohibit local interrupts (interrupts on the current processor) before acquiring the lock, or the interrupt handler may break the kernel code that is holding the lock, and may attempt to compete for this already held spin lock. As a result, the interrupt handler spins and waits for the lock to be re-usable, but the holder of the lock cannot run until the interrupt handler has finished executing, which can cause a double-request deadlock.

Spin lock and lower half: Because the lower half (the lower part of the interrupt program) can preempt code in the context of the process, the current half and the process context share data must be protected from the shared data in the context of the process, so it is necessary to lock the lower half of the execution. Similarly, because the interrupt handler can preempt the lower half, if the interrupt handler and the lower half share the data, then the appropriate lock must be acquired while the interrupt is forbidden. For soft interrupts, regardless of the same type, if the data is shared by a soft interrupt, it must be protected by a lock, since two soft interrupts of the same type can also run on multiple processors in a single system. However, a soft on the same processor is severed does not preempt another soft interrupt (GX : Because it is forbidden to respond to interrupts of the same type in the context of the interrupt handling code run? ) , so there is no need to prohibit the lower half.

Spin locks are primarily used in the kernel to prevent concurrent access to critical sections in multiple processors, preventing competition from kernel preemption. In addition, the spin lock does not allow task sleep (the task that holds the spin lock causes a self-deadlock-because sleep can cause the kernel task that holds the lock to be re-dispatched, and then reapply for the lock it has held), it can be used in the context of the interrupt .

The semaphore in the Lnux is a sleep lock. If there is a task trying to get a semaphore that has been held, the semaphore pushes it into the waiting queue and then lets it sleep. The processor then gets free to execute other code. When the semaphore-holding process releases the semaphore, a task in the waiting queue will be awakened, thereby obtaining the semaphore.

The sleep characteristics of the semaphore, which makes the semaphore suitable for long-time hold of the lock, can only be used in the context of the process, because the interrupt context is not scheduled, and when the code holds the semaphore, it can no longer hold the spin lock.

Although it sounds that the use of the two conditions is complex, in practice, the signal volume and spin lock is not easy to confuse. Note the following principles:

If the code needs to sleep-this is often the case when synchronizing with user space-the use of semaphores is the only option. Because it is not limited by sleep, the use of semaphores is generally simpler. If you need to choose between spin locks and semaphores, it depends on the length of time the lock is held. Ideally, all locks should be held as short as possible, but if the lock is held for a longer period of time, the use of the semaphore is a better choice. In addition, the semaphore differs from the spin lock, which does not turn off kernel preemption , so the code holding the semaphore can be preempted. This means that the semaphore does not negatively affect the scheduling response time.

--------spin lock to signal volume------------------------------------------------------

Lock-in method for demand recommendation

Low overhead lock priority using spin lock

Short-term lock priority with spin lock

Long-term lock priority use of semaphores

Lock using spin lock in interrupt context

Holding a lock is a need to sleep, dispatch the use of the semaphore

Atomic operations, semaphores, read and write semaphores, and spin locks:

http://kom118.blog.163.com/blog/static/476673182010312113630768/

Spin Locks and semaphores:

http://canlynet.blog.163.com/blog/static/2550136520091025069172/

Spin Lock: A mutex that waits for a lock to be acquired in a way that loops "test and set" when the lock is not acquired.

Get method: Use Test-and-set atomic operation to test and set a memory variable. --the method of implementing mutual exclusion.

Not interrupted: implemented by Forbidden Preemption.

Use cases: can be used in the process context and interrupt context.

Characteristics:

1, this lock can not be acquired when the system overhead, so the acquisition of locks and release locks of the interval code execution time should be as short as possible.

2. In a single CPU core preemption system, kernel preemption is forbidden during spin lock hold. However, in a single CPU core does not support preemption system, spin lock degradation is null operation. -that is, if the interval code that holds the lock takes too long to execute, there will be no response to other actions (false freezes).

3, because preemption is forbidden, the spin lock can guarantee that the critical zone is not affected by the "other CPU and internal CPU" preemption process process. (but can respond to interrupts, if the even interrupt does not respond, a specific lock function is required)

4, may be interrupted and the bottom half (BH) of the impact, for this, with the opening and closing interrupted, for this reason:

SPIN_LOCK_IRQ (), SPIN_UNLOCK_IRQ ()

Spin_lock_irqsave (), Spin_unlock_irqstore ()

SPIN_LOCK_BH (), SPIN_UNLOCK_BH ()

Please refer to the textbook or web search for specific meanings.

Spin lock Expansion: 1, read-write spin lock, 2, sequential lock, 3, read-copy-update (RCU)

******************************************************************

Semaphore: A synchronization mechanism that uses sleep to wait for a wake-up when a lock is not acquired.

Not interrupted: the means by which the reference is not found, but can be inferred as the same spin lock.

Get method: With spin lock.

Application: Because it causes sleep, it can only be used in the context of a process. but int down_trylock (struct Semphore *sem) can.

Characteristics:

When the lock is not acquired, it goes to sleep, and the system overhead is the time TSW for the context switch.

Spin lock and signal volume comparison:

1, when the lock is not available, the semaphore overhead is TSW (context switching time), the spin lock cost is the time to wait to acquire the Tcs, these two times the tradeoff between the use of which mechanism.

2, the semaphore can be used to protect the code containing the potential to cause blocking (that is, the protected code can cause sleep functions such as copy_to_user (), Copy_from_user ()), spin lock can not. Spin lock If you also use this code, when sleeping another inlet to acquire the lock, will enter the loop, and sleep time is generally relatively long, the system resource overhead time is too long, the resource exhaustion occurs, until the sleep process is awakened, the code executes, the resources are released. I can't think of a deadlock in a spin-lock zone. But this is what the textbook says.

3, the interrupt context can only use the spin lock, cannot use the semaphore. Because the interrupt context is not scheduled, but after the sleep of the context switch, need to schedule, in the context of the interruption sleep can only sleep permanently--The crash!

If a function requires a lock and then calls another function to try to request the lock, the code is deadlocked.

Obtaining multiple locks can be dangerous, however, if you have 2 locks called lock1 and Lock2, the code needs to be acquired simultaneously, and you have a potential deadlock. The solution to this problem is often simple: when multiple locks must be obtained, they should always be obtained in the same order, as long as the simple deadlock described above can be avoided by following this Convention.

If you suspect lock competition in damaging performance, you may find the Lockmeter tool useful, this patch is equipped with the kernel to measure the time spent on lock waits, by looking at this report you can quickly know whether locking the competition is really a problem.

For 2.6.10, there is a universal ring cache implementation available in the kernel, how to use its information to see <linux/kfifo.h>.

Several options to lock the way:

1, sometimes a shared resource is a simple integer value, for such cases, the kernel provides an atomic integer called atomic_t, defined in <asm/atomic.h>, atomic_t operation is very fast, because they know when possible to compile Translated into a machine instruction. There are a number of functions that support atomic_t operations.

atomic_t data items must be accessed through these functions, and if you pass an atomic term to a function that expects an integer argument, you will get a compilation error.

2. The kernel provides a set of functions to modify or test a single bit of an atom, as the entire operation takes place within one step, and no interruption can interfere. See <asm/bitops.h>, they are guaranteed to be atomic, in time on the SMP.

You can simulate a lock for an operation, but it is best to use a spin lock, a spin lock is well debugged, and it handles interrupts and kernel preemption well.

A section of the analog lock for the operation code:

/*try to set lock*/

while (Test_and_set_bit (NR,ADDR)! = 0)

Wait_for_a_while ();

/*do your work*/

/*release lock,and Check ... * *

If (Test_and_clear_bit (nr,addr) = = 0)

Something_went_wrong (); /*already release:error*/

For operation Example:

Static int main_init (void)

{

Unsigned long v = 0x00;

Unsigned log ret = Test_and_rest_bit (0,&V);

PRINTK (kern_info "%x,%x/n", ret,v);

Return 0;

}

The returned result is 0, 1.

3. Signal Volume

4. Spin Lock

5. Seqlock mechanism, see <linux/seqlock.h>

6, RCU (read-copy-update), see <linux/rcupdate.h>. Examples of using RCU in the real world are: <1>, network routing table, <2>, wireless IP Drive.

Rcu_read_lock () is fast and disables kernel preemption and is therefore atomic.

7, cpmpletion completion mechanism.

Atomic manipulation: An atomic context is just a state where multiple steps must be performed without any type of concurrent access

Linux spin lock and semaphore "turn"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.