Synchronization and mutual exclusion under Linux

Source: Internet
Author: User
Tags mutex semaphore

Synchronization and mutual exclusion under Linux

When it comes to the concurrency of Linux, it inevitably involves the synchronization and mutual exclusion between threads, and Linux mainly provides us with several ways to implement synchronous mutual exclusion between threads.

Mechanism, this paper mainly introduces the mutex, condition variables and semaphore. Mutexes and condition variables are included in the Pthread thread library and need to be included with the

<pthread.h> header file. You need to include the <semaphore.h> header file when using semaphores.

1. Mutual exclusion Lock

Type declaration: pthread_mutex_t mutex;

Initialize the mutex:

The program needs to initialize it before using pthread_mutex_t, and for statically assigned pthread_mutex_t variables,

As long as the Pthread_mutex_initializer is assigned to the variable, the statement is as follows:

Static pthread_mutex_t Mutex=pthread_mutex_initializer;

For a mutex variable that is dynamically allocated or does not have a default mutex property, the Pthread_mutex_init function is called to perform the initial chemical

For The function declaration is as follows:

int Pthread_mutex_init (pthread_mutex_t* mutex,const pthread_mutexattr_t* attr);

A mutex is a pointer to a mutex, attr is a pointer to a property structure body, and a default property is used when null.

It is important to note that the Pthread_mutex_init function can only be executed exactly once, and the result of repeated execution is undefined.

Operation on Mutex:

int Pthread_mutex_lock (pthread_mutex_t* mutex);//Perform a lock operation on the mutex

int Pthread_mutex_unlock (pthread_mutex_t* mutex);//unlock operation on mutex

The destruction of the mutex amount:

int Pthread_mutex_destroy (pthread_mutex_t* mutex);//

How to use:

The following code protects a critical section with a mutex:

pthread_mutex_t mutex=pthread_mutex_initializer;//Initialization

Pthread_mutex_lock (&mutex);//Get Lock

/*critical Section code*/

Pthread_mutex_unlock (&mutex);//Release lock

It is usually more appropriate to write a set of functions that access the critical section, placing the locking call in these functions, which is to make sure that the object is snapped to him

A method of sexual access, so that the locking mechanism is transparent to the calling thread.

2. Condition variables

Sometimes, we may need to wait until a certain condition is met before you can use a busy wait before using a condition variable, such as

The following code:

while (x!=y);

This way, however, this kind of manger does not take the crap of the behavior is very not advocated. Therefore, we introduce the concept of a conditional variable to be a thread in

A condition that is not satisfied is entered in a pending state.

Type declaration: pthread_cond_t cond;

To initialize a condition variable:

The program must initialize the pthread_cond_t variable before it is used. For statically allocated pthread_cond_t variables,

As long as the Pthread_cond_initializer is assigned to the variable, the statement is as follows:

pthread_cond_t Cond=pthread_cond_initializer;

For variables that are dynamically allocated or have no default properties, call the Pthread_cond_init function to perform the initialization. The function declaration is as follows:

int Pthread_cond_init (pthread_cond_t* cond,const pthread_cond_attr_t* attr);

Cond is a pointer to a condition variable, attr is a pointer to a property struct body, and a default property is used when null.

To manipulate a condition variable:

int pthread_cond_wait (pthread_cond_* cond,pthread_mutex_t* mutex);//causes the thread to block a condition.

int pthread_cond_signal (pthread_cond_t* cond);//wakes up a thread that is blocking on cond.

To destroy a condition variable:

int Pthread_cond_destroy (pthread_cond_t* cond);

How to use:

A condition variable is called with the test of an assertion or condition, which enables you to associate a condition variable to an assertion. Typically the thread will

A condition is tested, and if it fails, the pthread_cond_wait function is called to block the thread. The sample code is as follows:

Pthread_mutex_lock (&mutex);

while (A<B)

Pthread_cond_wait (&cond,&mutex);

Pthread_mutex_unlock (&mutex);

The calling thread should obtain a mutex before it tests or invokes pthread_cond_wait, to avoid having to test the condition with other

The value of the variable in the thread override condition. The second parameter in the Pthread_cond_wait function is a pointer to a mutex type that the thread calls

Pthread_cond_wait implicitly releases the mutex mutex and blocks it, allowing other threads to obtain the mutex and modify the assertion

The variable. When a thread is successfully returned from pthread_cond_wait, it again has a mutex and does not have to be explicitly re-

The amount of mutex.

When another thread modifies the value of a variable in an assertion, it can call the Pthread_cond_signal function to wake up a wait at an assertion to come true

The thread. You can also use the Pthread_cond_broadcast (pthread_cond_t*) function to wake up all waiting in a condition variable

On the thread. Obtain a mutex before modifying any of the variables that appear in the assertion. The sample code is as follows:

Pthread_mutex_lock (&mutex);

a++;

Pthread_cond_signal (&cond);//pthread_cond_broadcast (&cond);

Pthread_mutex_unlock (&mutex);

3. Signal Volume

The semaphore is an integer variable with two atomic operations of wait and signal. The wait operation can also be called a Down, p operation. Signal

can also be called up, V, post operations.

If S is greater than the 0,wait operation, it is reduced in one atomic operation. If s equals 0,wait operation, it's in an atomic operation.

Test S, block the invoker, put the caller in wait queue for wait.

If the thread is blocked on the semaphore, then s must equal the 0,signal operation to unblock a waiting thread. If S is greater than 0, that is

No thread is blocking the semaphore, and signal is doing incremental operations on S.

The semaphore can be understood as the amount of resources available in the critical section, and wait indicates the request for the resource, when there is no available resource, the semaphore is 0,signal

Represents the release of resources after a thread has used the resource.

Here are a few ways to control the execution of threads in some order by semaphore:

1. Thread 1 in a precedes thread 2 b execution [s initial session is 0]

Process 1:

A

Signal (&S);

Process 2:

Wait (&s);

b

2. In thread 1, a in thread 2, the B statement alternately executes [s,q initialized to 1]

Process 1:

while (1) {

Wait (&s);

A

Signal (&Q);

}

Process 2:

while (1) {

Wait (&q);

b

Signal (&S);

}

You can ensure that a or B is performed first by making S 0Q to 1, or by making S 1Q to 0.

It should be noted that in order to avoid the application of multiple resources to deadlock, should be in the same order to apply for resources, here the company interview often will be

asked.

The semaphore in Linux has a nameless semaphore and a named semaphore, the nameless semaphore can be used for synchronization and mutual exclusion between threads, and named semaphores are available

For inter-process communication, named semaphores are similar to named pipes and are stored on disk in the form of files.

Nameless semaphore:

Type declaration:

sem_t sem;

Initialization

int Sem_init (sem_t* sem,int pshared,int value);

The parameter pshared is 0, indicating that the semaphore can only be used by threads in the process that initialized the semaphore.

Value represents the values to initialize the SEM. Value cannot be negative.

Operation:

int sem_post (sem_t* sem);//signal operation

int sem_wait (sem_t* sem);//wait operation

Destroyed:

int Sem_destroy (sem_t* sem);

How to use:

The semaphore is typically initialized by calling Sem_init on the main thread first. Then call the post or wait function in another thread. Sample code

    • This article is from: Linux Tutorial Network

Synchronization and mutual exclusion under Linux

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.