Multi-thread synchronization in Linux and multi-thread synchronization in linux

Source: Internet
Author: User

Multi-thread synchronization in Linux and multi-thread synchronization in linux

When multiple threads share the same memory, make sure that each thread sees a consistent data view. When multiple threads modify the memory at the same time, there may be deviations, get the expected value. For the sake of synchronization, one thing must be logically ordered, even in a concurrent environment. However, the operating system will not automatically serialize multithreading, therefore, we need to use the synchronization api provided by the operating system, combined with our own business logic, and use multithreading to improve performance while ensuring the correctness of the business logic. Generally, there are four Synchronization Methods in linux: Atomic lock, mutex, read/write lock, and conditional variable. The following describes several Synchronization Methods.

1. spinlock

1) Concept

Spinlock is a mutually exclusive structure. It uses a special set of atomic commands provided by the CPU to achieve mutually exclusive access to a resource, which requires hardware support. When data access by one thread is not completed, other threads cannot access the same data.

2) Implementation

The spinlock is generally implemented based on the atomic read-modify-write operation. The read-modify-write operation allows a CPU to read a value, modify the value, and write the modified value back to the memory as an atomic bus operation, therefore, special CPU support is required. Specifically, the test-and-set command reads a value from the memory, compares it with 0, and sets the value in the memory to 1.

3) related functions

A) atomic operation

Test_and_set (volatile int * addr, value)

{

Return OS _atomic_test_and_set_int (addr, value );

}

Here the volatile modifier tells the compiler to get from memory to ensure correctness and avoid reading inaccurate values from registers.

B) set the lock variable

1 set_spinlock (lock_word) 2 {3 int I = 0; 4 int value; 5 while (true) 6 {7 value = test_and_set (& lock_word, 1 ); 8 if (value = 0) // You Can Get 9 break if it is not occupied. 10 else // It is occupied by other threads. Continue to rotate 11 do nothing12} 13}

 

C) reset the lock variable

1 reset_spinlock(lock_word)2 {3    test_and_set (lock_word, 0);4 } 

2. mutex

1) Concept

It works the same as spinlock to ensure mutual access to a resource.

2) related functions

Int pthread_mutex_lock (pthread_mutex_t * mutex)

Int pthread_mutex_trylock (pthread_mutex_t * mutex)

Int pthread_mutex_unlock (pthread_mutex_t * mutex)

The semantics of pthread_mutex_trylock () is similar to that of pthread_mutex_lock (). The difference is that EBUSY is returned when the lock is occupied rather than waiting.

3) Difference between the spinlock and mutex

A) scope of action: mutex is the kernel object, which can be used in multi-thread and multi-process synchronization. the scope of action of spinlock is limited to the current process (the lock variable is in the process) and is only applicable to multi-thread synchronization.

B) The spin lock depends on the hardware's atomic operation commands.

C) when the thread fails to get the spinlock, it will wait cyclically. At this time, the thread is in the running state and the CPU is idling. When the mutex fails to be obtained, the thread will be suspended and the thread is in the wait state, will not be scheduled by the kernel.

D) due to the characteristics of 3, switching to the waiting state or from the waiting state to the wake-up state involves CPU context switching, which is time consuming and generally requires 25us. In contrast, the price of spinlock is lower and the efficiency is higher.

E) due to the characteristics of 3, the spin lock will be idling, resulting in a waste of CPU time slice. If the user holds the lock for a long time, resulting in a long idling time, it is not worth the candle. Therefore, spinlock is more suitable for the use scenario of "Fast take and fast release.

 

3. read/write lock

1) Concept

Both the spinlock and mutex ensure that only one thread operates on the shared memory at the same time. A mutex lock is either locked or not locked. Only one thread can lock it at a time. The read/write status can be set to read/write. The read/write status is locked, and the read/write status is not locked. Compared with the first two, the read/write lock has a higher concurrency, allowing multiple threads to read shared memory at the same time.

2) related functions

Pthread_rwlock_rdlock (pthread_rwlock_t *); read lock

Pthread_rwlock_tryrdlock (pthread_rwlock_t *); non-blocking read lock

Pthread_rwlock_wrlock (pthread_rwlock_t *); write lock

Pthread_rwlock_trywrlock (pthread_rwlock_t *); non-blocking write lock

Pthread_rwlock_unlock (pthread_rwlock_t *); release the lock

 

4. Condition Variables

1) Concept

Conditional variables are another synchronization mechanism. They are used in combination with mutex locks to use locks to protect conditional variables and implement wake-up and wait mechanisms through conditional variables. In this way, threads are allowed to wait for specific conditions in a non-competitive manner.

2) related functions

Int pthread_cond_signal (pthread_cond_t * cond); // wake up a thread with a waiting Condition

Int pthread_cond_broadcast (pthread_cond_t * cond); // wake up all threads in the waiting Condition

Int pthread_cond_wait (pthread_cond_t * cond, pthread_mutex_t * mutex); // wait for the condition to occur.

3) Description

Before calling pthread_cond_wait, the thread needs to obtain the mutex. The caller passes the mutex to the function. The function sends the call thread to the waiting queue and unlocks the mutex. This operation is an atomic operation. When pthread_cond_wait is returned, the mutex is locked again. This implementation is implemented in the pthread_cond_wait function and does not require user logic intervention.

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.