Spin lock and read/write spin lock for kernel synchronization

Source: Internet
Author: User

Locking mechanism used in multiple CPU systems, when a CPU is accessing the critical section of the spin lock protection, the critical section will be locked, the other need to access the critical section of the CPU can only busy wait until the previous CPU has access to the critical section, the critical section unlocked. The spin lock allows the waiting thread to wait for the busy waits instead of sleep blocking, while the semaphore is causing the waiting thread to sleep. Spin-lock busy Waits waste processor time, but the time is usually very short, under 1 milliseconds.

Spin lock is used in multiple CPU systems, in a single processor system, the spin lock does not act as a lock, only to prohibit or enable kernel preemption. During a spin-lock busy Wait, the kernel preemption mechanism is still valid, and threads waiting for spin-lock release may be preempted by higher-priority threads.

Spin locks are based on shared variables. One thread acquires a lock by setting a value for the shared variable, and the other waits for the thread to query whether the shared variable is zero to determine if the lock is available, and then "spins" in a busy waiting loop until the lock is available.


Because of mutual exclusion, code that uses spin locks has no thread concurrency, and the performance of multiprocessor systems is limited. By observing the thread's access behavior in the critical section, we find that some threads simply read the information and do not modify anything, so allowing them to enter the critical section at the same time is not dangerous, but can greatly improve the concurrency of the system. This is a lock that distinguishes threads into readers and writes, multiple readers allow simultaneous access to shared resources, and application threads still use busy waits during the waiting period, which we call read-write spin locks (reader-writer Spinlock).

Properties for read-write spin locks

The shared resource mentioned above can be a simple single variable or multiple variables, or it can be a complex data structure like a file. To prevent errors caused by the use of read-write spin locks, we assume that each shared resource is associated with a unique read-write spin lock, and that the thread only allows access to shared resources in a similar way to elephant-mounted refrigerators:

    1. Apply for the lock.

    2. After acquiring the lock, read and write the shared resource.

    3. Release the lock.

Some user-configured read-write lock support threads continue to apply for the same type of lock while holding the lock, and the reader transforms the identity writer in the case of a lock. These 2 properties are not meaningful for read-write spin locks for short critical areas, so this article is not discussed.

For thread execution, let's assume that:

    1. The system has a global clock, we discuss the time is discrete, not continuous, mathematical sense of time.

    2. At any one time, the total number of active threads in the system is limited.

    3. The execution of the thread is not delayed indefinitely due to scheduling, missing pages exception, and so on. Theoretically, the execution of a thread can be delayed indefinitely by the system, so any mutex algorithm has a risk of deadlock. We want to eliminate the interference of the system, focus on the algorithm and the implementation itself.

    4. The thread's access to the shared resource ends within a limited step.

    5. When a thread releases a lock, we want the thread to release the lock within a finite step.

    6. Because each program step takes a limited amount of time, if the above 5 conditions are met, the thread that gets the lock will inevitably release the lock for a limited period of time.

We say that a read-write spin lock algorithm is correct, meaning that the lock satisfies the following three properties:

1. Mutex. At any time the reader and the writer cannot access the shared resource at the same time (that is, acquire the lock); At any time only one writer can access the shared resource.

2. Reader concurrency. Multiple readers can access shared resources at the same time by satisfying the "mutex" condition.

3. No deadlock (Freedom from Deadlock). If thread a attempts to acquire a lock, then a thread is bound to acquire a lock, and the thread may be a self, and if thread a tries but never acquires a lock, then one or some of the threads must acquire the lock indefinitely.

Read-write spin locks are primarily used to compare short snippets of code, while thread waits should not go to sleep, because sleep/wake operations are time consuming and greatly extend the wait time for locks, so we ask:

4. Busy waiting. The thread that is requesting the lock must constantly query whether an exit waiting event occurs and cannot go to sleep. This requirement only describes the behavior of the thread when the lock request operation is unsuccessful, and does not involve the correctness of the lock itself.

The "no deadlock" property tells us that the application thread must get the lock globally, but for some or some of the application threads, they may never get a lock, a phenomenon known as starvation (starvation). One reason stems from the features of a computer architecture: for example, in a multicore system that uses read-write spin locks based on a single shared variable, if the lock holder A is located next to the processor where the waiting person B is located (perhaps sharing a level two cache), B is more likely to know that the lock is released, increasing the chance of acquiring a lock, Threads on a remote processor are more difficult to PK, leading to starvation. Another reason stems from the design strategy of threads that read and write spin locks deliberately preferring certain types of roles.

In order to improve concurrency, read-write spin locks can choose to prefer readers, that is, the reader has priority to obtain the lock:

1. Reader preference (reader Preference). If the lock is held by the reader, the new reader can get the lock immediately without having to wait. When a lock is "written" or "not held", the new reader can "inclusions" to the waiting writer, depending on the implementation.

If the reader continues to arrive, the waiting writer is likely to never get a lock, leading to starvation. In reality, the number of the writer is generally much less than the reader, and the frequency of arrival is very low, so read-write spin lock can choose preference writer to effectively alleviate hunger phenomenon:

2. Writing is preferred (writer Preference). The writer must obtain a lock before the reader/writer. Because the number of waiting threads that arrive before the writer is limited, the waiting time for the writer is guaranteed to have a reasonable upper bound. However, the order in which the locks are acquired between multiple readers is uncertain, and the first-to-last reader may not be able to obtain a lock before the writer. It can be seen that if the writer continues to arrive, the reader may still produce hunger.

In order to eradicate hunger completely, the perfect read-write spin lock also needs to meet any of the following properties:

3. No hunger (Freedom from starvation). If thread a attempts to acquire a lock, then a must be able to acquire the lock for a limited time. Of course, this "limited time" may be quite lengthy.

4. Fairness (fairness). We have divided the execution of the "lock request" operation into two phases: the preparation phase (Doorway section), which can be completed at the limited procedure step, the wait phase (waiting section), and perhaps never end the wait phase once the thread is finished, the threads are read-write spin locks. If threads A and B request a lock at the same time, but the wait phase of a is completed before B, then a fair read-write spin lock guarantees A lock before B. If the wait phase of a and B overlap in time, then the order in which they acquire locks is indeterminate (in chapter II we completely remove the "overlap" concept).

"Fair" means that the thread applying for the lock must acquire a lock for a limited period of time. If not, suppose a applies for a fair read and write spin lock but never gets it, then the thread that completes the prep phase after A is obviously never able to get a lock. But before a or "overlap" to complete the waiting phase of the number of application threads is limited, it is inevitable that a "deadlock", contradictions. It also shows that the time to release the lock is limited. Using a fair read-write spin lock eliminates the hunger phenomenon, assuming that the thread accesses the shared resource and frees the lock for a reasonable upper bound, then the lock request thread waits only on the number of threads that were waiting before, and does not depend on other factors.


Spin lock and read/write spin lock for kernel synchronization

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.