Comparison between spin lock and mutex -- multi-core programming study Note 2

Source: Internet
Author: User

A spin lock is a non-blocking lock. That is to say, if a thread needs to obtain the spin lock but the lock has been occupied by other threads, the thread will not be suspended, instead, it is constantly consuming CPU time and constantly trying to obtain the spin lock.

The mutex is a blocking lock. When a thread cannot obtain the mutex, the thread will be suspended directly, and the thread no longer consumes CPU time. When other threads release the mutex, the operating system will activate the suspended thread and put it into operation.

The two locks apply to different scenarios:

If it is a multi-core processor, it is cost-effective to use the spin lock if it is estimated that the thread waits for the lock for a short time and is shorter than the thread's two context switches.

If it is a multi-core processor, if it is estimated that the thread waits for a lock for a long time, at least longer than the two thread context switches, we recommend that you use mutex.

If it is a single-core processor, it is generally not recommended to use a spin lock. Because only one thread is in the running state at the same time, if the running thread finds that the lock cannot be obtained, it can only wait for unlocking, but because it does not stop, therefore, the thread that gets the lock cannot enter the running state. It can be scheduled only when the running thread has used up the time slice allocated to the operating system. In this case, it is costly to use the spin lock.

If the lock code is often called, but the competition rarely happens, the spin lock should be used first. The spin lock overhead is relatively small and the mutex overhead is large.

References

Multi-core Programming Technology

Linux kernel design and implementation

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.