Differences between semaphores and spin locks

Source: Internet
Author: User

Differences between semaphores and spin locks

The spin lock does not cause the caller to sleep.If the spin lock has been maintained by another execution unit, the caller will keep repeating to check whether the lock holder has released the lock. "Spin" means "in situ ".The semaphore causes the caller to sleep.It will drag the process out of the running queue unless the lock is obtained.

------------------------------------------------------
Although the conditions for use between the two are complex, in fact, in actual use, semaphores and spin locks are not easy to confuse. Note the following principles:
If the code needs to sleep-- This usually happens when it is synchronized with the user space --Using semaphores is the only choice. Because it is not restricted by sleep, it is generally easier to use semaphores.If you need to choose between the spin lock and semaphore, it depends on the length of time the lock is held. Ideally, all locks should be held as short as possible, but it is better to use semaphores if the lock is held for a long time.
Select.In addition, unlike the spin lock, semaphores do not disable kernel preemption, so the code holding semaphores can be preemptible.This means that the semaphore will not have a negative impact on the scheduling response time.

Semaphores
------------------------------------------------------
Recommended locking method

The spin lock is preferred for low-cost locking.
Short-term locks give priority to spin locks
Apply spin lock to intercept context locking

Semaphores are preferentially used for long-term locking.
Holding locks requires sleep and scheduling to use semaphores.
--------------------------------
Spin lock
------------------------------------------------------
Spin lock is a kind of lock designed to prevent multi-processor concurrency. It is widely used in interrupt processing and other parts in the kernel (For a single processor, to prevent the concurrency in the interrupt processing, you can simply close the interrupt, without the need for spin locks ).
A spin lock can only be held by one kernel task at most. If a kernel task attempts to request a spin lock that has been used (held, then this task will always be busy loop-rotate-Wait for the lock to be available again. If the lock is not in contention, the kernel task requesting it will immediately get it and continue. The spin lock can prevent more than one kernel task from entering the critical section at any time. Therefore, this lock can effectively avoid competition for shared resources for Kernel Tasks running concurrently on the multi-processor.
The basic form of the spin lock is as follows:
Spin_lock (& mr_lock );
// Critical section
Spin_unlock (& mr_lock );

Because the spin lock can only be held by up to one kernel task at a time point, only one thread is allowed to exist in the critical section at a time point. This satisfies the locking service required by Symmetric Multi-processing machines.On the single processor, the spin lock is only used as a switch to set kernel preemption.If the kernel preemptible does not exist, the spin lock will be completely removed from the kernel during compilation.
To put it simply, spin locks are mainly used in the kernel to prevent concurrent access to the critical zone in the multi-processor and to prevent competition caused by kernel preemption.In addition, the spin lock does not allow the task to sleep (the task holding the spin lock will cause a self-deadlock.--Because sleep may cause the kernel task holding the lock to be rescheduled, and apply for the lock that you already hold again), Which can be used in the interrupt context.
Deadlock: Assume one or more kernel tasks and one or more resources. Each kernel is waiting for one of these resources, but all resources are occupied. In this case, all kernel tasks are waiting for each other, but they will never release the occupied resources. Therefore, no kernel task can obtain the required resources and continue running, this means that the deadlock has occurred. Self-occupation means that you possess a certain resource, and then apply for the resource that you already possess. Obviously, it is impossible to obtain the resource again.

I. Why is spin lock used?
   The basic principle of the operating system lock mechanism is that it cannot be intertwined with other lock operations during a lock operation, to avoid confusion caused by multiple execution paths simultaneously operating some important data and data structures in the kernel. In different system environments, the lock mechanism can be implemented in multiple ways according to the system characteristics and operation requirements.Taking Linux as an example, the lock mechanism of the system kernel is generally implemented in three basic methods: primitive, Guanzhong, and bus locks..

In a single CPU system, the read-Modify-write primitive of the CPU can be atomic, that is, the execution process will not be interrupted, so the CPU is disconnected through Guanzhong, at the chip level, the data accessed by this operation cannot be simultaneously accessed by Multiple kernel control paths to avoid cross-execution.However,In a symmetric multi-processor (SMP) environment, the read-Modify-write primitive involved in a single CPU is no longer atomic, because, multiple bus operations are performed when a CPU executes read-Modify-write commands.
Competing bus can lead to the intersection of read-write operations on the same storage unit with other CPUs
,In this case, we need to use an original object called spin lock to provide the lock Bus Method for the CPU..

Ii. What is a spin lock?
    Spin lock is a typical mutex Method for critical resources,Its name comes from its features. To obtain a spin lock, the code running on a CPU must first perform an atomic operation to test and set a memory variable (test-and-set, because it is an atomic operation, it is impossible for other CPUs to access this memory variable before the operation is completed. If the test result shows that the lock is idle, the program obtains the spin lock and continues execution. If the test result shows that the lock is still in use,The program repeats the "test-and-set" operation in a small loop to start "Spin ".Finally, the lock owner releases the spin lock by resetting the variable. Therefore, a pending test-and-set operation reports to its caller that the lock has been released.

Iii. Several facts about spin locks
  The spin lock is actually a waiting lock. When the lock is unavailable, the CPU continuously executes the "test-and-set" lock until it is available, the CPU does not do any useful work while waiting for the spin lock, just waiting. This indicates that it is reasonable to use the spin lock only when the lock occupation time is very short, because a CPU may be waiting for the spin lock at this time. When the critical section is relatively short for an hour, for example, to ensure the atomicity of data modification, spin locks are commonly used. When the critical section is large or has a shared device, it takes a long time to occupy the lock, using the spin lock is not a good choice, it will reduce the CPU efficiency.
  The spin lock also has a deadlock issue. The most common cause of this problem is to apply a spin lock recursively, that is, if a CPU that already has a spin lock wants to obtain the spin lock for the second time, the CPU will be deadlocked. The spin lock does not have a "use counter" or "Owner ID" associated with it; the lock is occupied or idle. If you obtain the lock when it is occupied, you will wait until it is released. If your CPU already has the lock, the code used to release the lock will not run, because you keep the CPU in the spin state of a memory variable "test and set. In addition, if the process gets a spin lock and then blocks it, it may also lead to a deadlock. The deadlock caused by the spin lock will cause the entire system to be suspended and the impact will be very great.
 The spin lock must be called by the system kernel. It is impossible to request spin locks from users in user programs. When a user process has a spin lock, the kernel is to upgrade the code to the level of the tube state to run. Internally, the inner nuclear energy gets the spin lock, but no one can do this.

Iv. Comparison of spin locks and semaphores
    Spin locks and semaphores are the basic methods to solve the mutex problem.,Whether it is a single processing system or a multi-processing system, they can be transplanted without modifying the code.So how should we choose these two methods? This requires consideration of the nature of the critical section and the requirements for system processing.
   Strictly speaking,Semaphores and spin locks are mutually exclusive methods at different levels. The implementation of the former depends on the latter.
Semaphores are process-level and are used for resource mutual exclusion between multiple processes. Although they are also in the kernel, the kernel execution path is a process that represents the process to compete for resources.
.If the competition fails, context switches will occur, and the process can sleep, but the CPU will not stop, and other execution paths will be run. In terms of concept, this is not directly related to a single CPU or multiple CPUs, but only in the implementation of the semaphore itself, in order to ensure the atomicity of the semaphore structure access, spin locks are required in multiple CPUs for mutual exclusion. However, it is worth noting that context switching takes a certain period of time and will cause high-speed buffering to fail, which has a great impact on system performance..Therefore, semaphores are a good choice only when a process occupies resources for a long time.
   When the critical zone to be protected is relatively short, It is very convenient to use the spin lock because it saves the context switching time.However, if the CPU does not get the spin lock, it will be idling there until the lock is successful. Therefore, the lock must not stay in the critical section for a long time. Otherwise, the system efficiency will be reduced.

  To sum up,A spin lock is a primitive method to protect data structures or code segments. It is mainly used in SMP and used for CPU synchronization.Only one process is allowed to access the code in the critical section at a certain time.Its implementation is based on the CPU to lock the Data Bus command. To ensure system efficiency, the critical zone of spin lock is generally relatively short. In a single CPU system, the use of spin locks is of little significance, and it is easy to cause deadlocks due to recursive call of spin locks.

Semaphores
------------------------------------------------------
Semaphores in Linux are sleep locks. If a task tries to obtain an held semaphore, the semaphore will push it into the waiting queue and then sleep it. In this case, the processor is free to execute other code. When the process holding the semaphore releases the semaphore, a task in the waiting queue will be awakened to obtain the semaphore.
The sleep feature of semaphores makes the semaphores suitable for cases where the lock is held for a long time. They can only be used in the process context because the interrupt context cannot be scheduled; in addition, when the Code holds a semaphore, it cannot hold a spin lock.

The basic usage of semaphores is as follows:
Static declare_mutex (mr_sem); // declare mutex semaphores
If (down_interruptible (& mr_sem ))
// Interrupted sleep. When the signal arrives, the sleep task is awakened.
// Critical section
Up (& mr_sem );

Differences between semaphores and spin locks

The spin lock does not cause the caller to sleep.If the spin lock has been maintained by another execution unit, the caller will keep repeating to check whether the lock holder has released the lock. "Spin" means "in situ ".The semaphore causes the caller to sleep.It will drag the process out of the running queue unless the lock is obtained.

------------------------------------------------------
Although the conditions for use between the two are complex, in fact, in actual use, semaphores and spin locks are not easy to confuse. Note the following principles:
If the code needs to sleep-- This usually happens when it is synchronized with the user space --Using semaphores is the only choice. Because it is not restricted by sleep, it is generally easier to use semaphores.If you need to choose between the spin lock and semaphore, it depends on the length of time the lock is held. Ideally, all locks should be held as short as possible, but it is better to use semaphores if the lock is held for a long time.
Select.In addition, unlike the spin lock, semaphores do not disable kernel preemption, so the code holding semaphores can be preemptible.This means that the semaphore will not have a negative impact on the scheduling response time.

Semaphores
------------------------------------------------------
Recommended locking method

The spin lock is preferred for low-cost locking.
Short-term locks give priority to spin locks
Apply spin lock to intercept context locking

Semaphores are preferentially used for long-term locking.
Holding locks requires sleep and scheduling to use semaphores.
--------------------------------
Spin lock
------------------------------------------------------
Spin lock is a kind of lock designed to prevent multi-processor concurrency. It is widely used in interrupt processing and other parts in the kernel (For a single processor, to prevent the concurrency in the interrupt processing, you can simply close the interrupt, without the need for spin locks ).
A spin lock can only be held by one kernel task at most. If a kernel task attempts to request a spin lock that has been used (held, then this task will always be busy loop-rotate-Wait for the lock to be available again. If the lock is not in contention, the kernel task requesting it will immediately get it and continue. The spin lock can prevent more than one kernel task from entering the critical section at any time. Therefore, this lock can effectively avoid competition for shared resources for Kernel Tasks running concurrently on the multi-processor.
The basic form of the spin lock is as follows:
Spin_lock (& mr_lock );
// Critical section
Spin_unlock (& mr_lock );

Because the spin lock can only be held by up to one kernel task at a time point, only one thread is allowed to exist in the critical section at a time point. This satisfies the locking service required by Symmetric Multi-processing machines.On the single processor, the spin lock is only used as a switch to set kernel preemption.If the kernel preemptible does not exist, the spin lock will be completely removed from the kernel during compilation.
To put it simply, spin locks are mainly used in the kernel to prevent concurrent access to the critical zone in the multi-processor and to prevent competition caused by kernel preemption.In addition, the spin lock does not allow the task to sleep (the task holding the spin lock will cause a self-deadlock.--Because sleep may cause the kernel task holding the lock to be rescheduled, and apply for the lock that you already hold again), Which can be used in the interrupt context.
Deadlock: Assume one or more kernel tasks and one or more resources. Each kernel is waiting for one of these resources, but all resources are occupied. In this case, all kernel tasks are waiting for each other, but they will never release the occupied resources. Therefore, no kernel task can obtain the required resources and continue running, this means that the deadlock has occurred. Self-occupation means that you possess a certain resource, and then apply for the resource that you already possess. Obviously, it is impossible to obtain the resource again.

I. Why is spin lock used?
   The basic principle of the operating system lock mechanism is that it cannot be intertwined with other lock operations during a lock operation, to avoid confusion caused by multiple execution paths simultaneously operating some important data and data structures in the kernel. In different system environments, the lock mechanism can be implemented in multiple ways according to the system characteristics and operation requirements.Taking Linux as an example, the lock mechanism of the system kernel is generally implemented in three basic methods: primitive, Guanzhong, and bus locks..

In a single CPU system, the read-Modify-write primitive of the CPU can be atomic, that is, the execution process will not be interrupted, so the CPU is disconnected through Guanzhong, at the chip level, the data accessed by this operation cannot be simultaneously accessed by Multiple kernel control paths to avoid cross-execution.However,In a symmetric multi-processor (SMP) environment, the read-Modify-write primitive involved in a single CPU is no longer atomic, because, multiple bus operations are performed when a CPU executes read-Modify-write commands.
Competing bus can lead to the intersection of read-write operations on the same storage unit with other CPUs
,In this case, we need to use an original object called spin lock to provide the lock Bus Method for the CPU..

Ii. What is a spin lock?
    Spin lock is a typical mutex Method for critical resources,Its name comes from its features. To obtain a spin lock, the code running on a CPU must first perform an atomic operation to test and set a memory variable (test-and-set, because it is an atomic operation, it is impossible for other CPUs to access this memory variable before the operation is completed. If the test result shows that the lock is idle, the program obtains the spin lock and continues execution. If the test result shows that the lock is still in use,The program repeats the "test-and-set" operation in a small loop to start "Spin ".Finally, the lock owner releases the spin lock by resetting the variable. Therefore, a pending test-and-set operation reports to its caller that the lock has been released.

Iii. Several facts about spin locks
  The spin lock is actually a waiting lock. When the lock is unavailable, the CPU continuously executes the "test-and-set" lock until it is available, the CPU does not do any useful work while waiting for the spin lock, just waiting. This indicates that it is reasonable to use the spin lock only when the lock occupation time is very short, because a CPU may be waiting for the spin lock at this time. When the critical section is relatively short for an hour, for example, to ensure the atomicity of data modification, spin locks are commonly used. When the critical section is large or has a shared device, it takes a long time to occupy the lock, using the spin lock is not a good choice, it will reduce the CPU efficiency.
  The spin lock also has a deadlock issue. The most common cause of this problem is to apply a spin lock recursively, that is, if a CPU that already has a spin lock wants to obtain the spin lock for the second time, the CPU will be deadlocked. The spin lock does not have a "use counter" or "Owner ID" associated with it; the lock is occupied or idle. If you obtain the lock when it is occupied, you will wait until it is released. If your CPU already has the lock, the code used to release the lock will not run, because you keep the CPU in the spin state of a memory variable "test and set. In addition, if the process gets a spin lock and then blocks it, it may also lead to a deadlock. The deadlock caused by the spin lock will cause the entire system to be suspended and the impact will be very great.
 The spin lock must be called by the system kernel. It is impossible to request spin locks from users in user programs. When a user process has a spin lock, the kernel is to upgrade the code to the level of the tube state to run. Internally, the inner nuclear energy gets the spin lock, but no one can do this.

Iv. Comparison of spin locks and semaphores
    Spin locks and semaphores are the basic methods to solve the mutex problem.,Whether it is a single processing system or a multi-processing system, they can be transplanted without modifying the code.So how should we choose these two methods? This requires consideration of the nature of the critical section and the requirements for system processing.
   Strictly speaking,Semaphores and spin locks are mutually exclusive methods at different levels. The implementation of the former depends on the latter.
Semaphores are process-level and are used for resource mutual exclusion between multiple processes. Although they are also in the kernel, the kernel execution path is a process that represents the process to compete for resources.
.If the competition fails, context switches will occur, and the process can sleep, but the CPU will not stop, and other execution paths will be run. In terms of concept, this is not directly related to a single CPU or multiple CPUs, but only in the implementation of the semaphore itself, in order to ensure the atomicity of the semaphore structure access, spin locks are required in multiple CPUs for mutual exclusion. However, it is worth noting that context switching takes a certain period of time and will cause high-speed buffering to fail, which has a great impact on system performance..Therefore, semaphores are a good choice only when a process occupies resources for a long time.
   When the critical zone to be protected is relatively short, It is very convenient to use the spin lock because it saves the context switching time.However, if the CPU does not get the spin lock, it will be idling there until the lock is successful. Therefore, the lock must not stay in the critical section for a long time. Otherwise, the system efficiency will be reduced.

  To sum up,A spin lock is a primitive method to protect data structures or code segments. It is mainly used in SMP and used for CPU synchronization.Only one process is allowed to access the code in the critical section at a certain time.Its implementation is based on the CPU to lock the Data Bus command. To ensure system efficiency, the critical zone of spin lock is generally relatively short. In a single CPU system, the use of spin locks is of little significance, and it is easy to cause deadlocks due to recursive call of spin locks.

Semaphores
------------------------------------------------------
Semaphores in Linux are sleep locks. If a task tries to obtain an held semaphore, the semaphore will push it into the waiting queue and then sleep it. In this case, the processor is free to execute other code. When the process holding the semaphore releases the semaphore, a task in the waiting queue will be awakened to obtain the semaphore.
The sleep feature of semaphores makes the semaphores suitable for cases where the lock is held for a long time. They can only be used in the process context because the interrupt context cannot be scheduled; in addition, when the Code holds a semaphore, it cannot hold a spin lock.

The basic usage of semaphores is as follows:
Static declare_mutex (mr_sem); // declare mutex semaphores
If (down_interruptible (& mr_sem ))
// Interrupted sleep. When the signal arrives, the sleep task is awakened.
// Critical section
Up (& mr_sem );

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.