Several locks in a C + + thread

Source: Internet
Author: User
Tags mutex semaphore

The locks between threads are: mutexes, conditional locks, spin locks, read and write locks, and recursive locks. Generally, the more powerful the lock, the lower the performance.

1, mutual exclusion lock

A mutex is a semaphore that controls the mutual access of multiple threads to shared resources between them. This is to prevent multiple threads from manipulating a shared resource at a time. For example, there are multiple idle threads and a task queue in the thread pool. Any one thread is to use the mutex mutex to access the task queue to avoid the simultaneous access of multiple threads to the task queue for confusion.

At some point, only one thread can acquire the mutex, and no other thread will get the mutex until the mutex is released. If other threads want to acquire this mutex, the thread can only wait in a blocking manner.

Header file:<pthread.h>

Type: pthread_mutex_t,

Functions: Pthread_mutex_init (pthread_mutex_t * Mutex, const phtread_mutexattr_t * mutexattr);//Dynamic creation of locks, equivalent to new dynamic creation of an object

Pthread_mutex_destory (pthread_mutex_t *mutex)//release mutex, equivalent to delete

pthread_mutex_t Mutex = pthread_mutex_initializer;//Creates a lock in a static manner

Pthread_mutex_lock (pthread_mutex_t *mutex)//run in a blocking manner. If the previous mutex is locked, then the program will block here.

Pthread_mutex_unlock (pthread_mutex_t *mutex)

int Pthread_mutex_trylock (pthread_mutex_t * mutex);//attempts to lock the mutex. Returns non 0 if the mutex was previously locked, or if the mutex is not locked, the function returns and locks the mutex

This function is run in a non-blocking manner. That is, if the mutex was previously locked, the function would return non-0, and the program would continue to execute.

2. Conditional lock

Conditional locks are called condition variables, and a thread can use conditional variables to make the program block when a condition is satisfied. Once the condition satisfies a "semaphore" way to wake up a thread that is blocked because of that condition. The most common is in a thread pool where the task queue is empty when there is no task at first, and the thread pool is blocked because the "task queue is empty" condition. Once a task comes in, it wakes up a thread to handle the task in the form of a semaphore. In this process, the conditional variable pthread_cond_t is used.

Header file:<pthread.h>

Type: pthread_cond_t

Functions: Pthread_cond_init (pthread_cond_t * condtion, const phtread_condattr_t * condattr);//dynamic initialization of conditional variables, equivalent to new object creation

Pthread_cond_destory (pthread_cond_t * condition);//Release condition variable for dynamic request, equivalent to delete release object

pthread_cond_t condition = pthread_cond_initializer;//static initialization condition variable

Pthread_cond_wait (pthread_cond_t * cond, pthread_mutex_t * mutex);//The function is executed in a blocking manner. If a program in a thread executes the function, the thread waits until it receives a signal from the pthread_cond_signal or Pthread_cond_broadcast function to wake up.

Note: The semantics of the pthread_cond_wait function are equivalent to: first unlock the mutex, then wait for the signal of the condition variable in blocking mode, and then lock the mutex when the signal is received.

To prevent "spurious wakeup," the function is generally placed in the while loop body. For example

    1. Pthread_mutex_lock (mutex); //Plus mutual exclusion lock
    2. while (conditions are not valid)//When the condition variable in the front thread is not valid
    3. {
    4. Pthread_cond_wait (cond, mutex); //unlock, other threads make the condition set to send a signal, plus lock.
    5. }
    6. ... //operations on shared resources between processes
    7. Pthread_mutex_unlock (mutex); //Release Mutex

Pthread_cond_signal (pthread_cond_t * cond);//Change the thread in another thread, and the condition satisfies the sending signal. Wakes up a waiting thread (there may be multiple threads in a blocked state), and wakes up which thread is determined by the specific thread scheduling policy

Pthread_cond_broadcast (pthread_cond_t * cond);//Wake up all threads that are blocked because of this condition variable in broadcast form, wake up which thread is determined by the specific thread scheduling policy

Pthread_cond_timedwait (pthread_cond_t * cond, pthread_mutex_t * Mutex, struct timespec * time);//wait in a blocking manner, If the time is up, the condition is not met or it ends.

3. Spin Lock

The two previous locks are more common locks and are easier to understand. The following comparison between the mutual exclusion lock and the principle of spin lock, which is very helpful to really understand the spin lock.

Suppose we have a two processor core1 and Core2 computer, and now there are two threads in the program running on this computer: T1 and T2 are running on the processor Core1 and Core2 respectively, and a resource is shared between two threads.

First we explain how the mutex works, and the mutex is a sleep-waiting lock. Assuming that the thread T1 acquires the mutex and is running on Core1, the thread T2 also wants to acquire the mutex (Pthread_mutex_lock), but T1 is blocked because T2 is using a mutex. When T2 is in a blocking state, T2 is placed in the wait queue, and the processor Core2 handles other tasks without having to wait (busy, etc.). This means that the processor is not idle because the thread is blocked, and it handles other transactions.

Since the spin lock is different, the spin lock is a busy-waiting lock. In other words, if T1 is using a spin lock, and T2 is also applying for the spin lock, T2 will not get the spin lock at this time. Contrary to the mutex, the processor that runs T2 at this time Core2 continuously checks to see if the lock is available (Spin lock request) until the spin lock is acquired.

From the "Spin lock" name can also be seen, if a thread wants to get a used spin lock, then it will be consistent CPU request this spin lock so that the CPU can not do other things, until the lock is acquired, this is the meaning of "spin".

When blocking occurs, the mutex allows the CPU to handle other tasks, while the spin lock keeps the CPU constantly circulating requests to acquire the lock. By comparing the two meanings we know that "spin lock" is CPU-intensive

Header file:<linux\spinlock.h>

Type of spin lock: spinlock_t

Correlation function: Initialize: Spin_lock_init (spinlock_t *x);

Spin_lock (x); Only returns if the lock is obtained, otherwise it has been "spin"

spin_is_locked (x)//The macro is used to determine whether the spin lock x has been held by an execution unit (that is, locked), and if so, returns True, otherwise false.

Note: Spin locks are suitable for short-time, lightweight locking mechanisms.

4. Read/write Lock

When it comes to reading and writing locks, we can use the reader-writer problem to understand. First of all, let's simply say "reader-writer".

Some of the data in the computer is shared by multiple processes, and there are two types of operations on the database: one is read, the data is read from the database, the content in the database is not modified, and the write operation modifies the data stored in the database. As a result, we allow multiple "read" operations to be performed on the database at the same time, but there is only one "write" operation on the database at a time to update the data. This is a simple reader-writer model.

Several locks in a C + + thread

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.