Linux thread synchronization and mutex

Source: Internet
Author: User

● Mutex lock

The mutex lock is used to ensure that only one thread is executing a code segment (critical section) within the same time period ). The most vulnerable to multi-threaded programming is the definition and access of critical zones.
Control. The following is a simple example of a producer and a consumer. The producer and consumer share a buffer zone. It is assumed that the buffer zone can only store one message.

#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <sys/time.h>static char buff[50];int have_msg=0;pthread_mutex_t mutex;int delay=1;void consumeItem(char *buff){    printf("consumer item\n");}void produceItem(char *buff){    printf("produce item\n");}void *consumer(void *param){    while (1)    {        pthread_mutex_lock(&mutex);        if (have_msg>0)        {            have_msg--;            consumeItem(buff);        }        pthread_mutex_unlock(&mutex);        sleep(delay);    }    return NULL;}void *producer(void *param){    while (1)    {        pthread_mutex_lock(&mutex);        if (have_msg==0)        {            have_msg++;            produceItem(buff);        }        pthread_mutex_unlock(&mutex);        sleep(delay);    }    return NULL;}int main(){    pthread_t tid_c, tid_p;    void *retval;    pthread_mutex_init(&mutex, NULL);    pthread_create(&tid_p, NULL, producer, NULL);    pthread_create(&tid_c, NULL, consumer, NULL);    pthread_join(tid_p, &retval);    pthread_join(tid_c, &retval);    return 0;}

The output must be like this:

The simplest use of mutex lock is as follows:
Pthread_mutex_t mutex; // defines the lock.
Pthread_mutex_init (& mutex, NULL); // default attribute initialization lock
Pthread_mutex_lock (& mutex); // apply for a lock
...
Pthread_mutex_unlock (& mutex); // release the lock
Set lock attributes
The pthread_mutexattr_setpshared function and the pthread_mutexattr_settype function are used to set the mutex lock attribute.
The previous function sets the property pshared, which has two values: PTHREAD_PROCESS_PRIVATE and PTHREAD_PROCESS_SHARED. The former is used to synchronize threads in different processes, and the latter is used to synchronize different threads in the process. In the preceding example, we use the default PTHREAD_PROCESS _ PRIVATE attribute. The latter is used to set mutex lock types. Optional types include PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_ERRORCHECK, PTHREAD_MUTEX_RECURSIVE, and PTHREAD _ MUTEX_DEFAULT. They define different on-board and unlock mechanisms. Generally, the last default attribute is used. The usage is as follows:

pthread_mutexattr_t mutexAttr;pthread_mutexattr_init(&mutexAttr);pthread_mutexattr_setpshared(&mutexAttr, PTHREAD_PROCESS_PRIVATE);pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_DEFAULT);pthread_mutex_init(&mutex, &mutexAttr);

Pthread_mutex_lock: The thread is blocked until pthread_mutex_unlock is called.
Another two functions can be used: int pthread_mutex_trylock (pthread_mutex_t * _ mutex). This function returns immediately and determines whether the lock is successful Based on the returned status. Int pthread_mutex_timedlock (pthread_mutex_t * mutex, struct timespec * _ restrict). This function returns a timeout value.
Mutex is mainly used for mutex access to critical zones. Used for thread mutex.

● Condition Variables

A condition variable is used to block a thread and wait for an event. When a waiting event occurs, the blocking thread is notified.
An obvious disadvantage of mutex is that it has only two States: Locked and non-locked. Conditional variables make up for the lack of mutex lock by allowing the thread to block and wait for another thread to send signals.Often used together with mutex lock. When used, the condition variable is used to block a thread. When the condition is not met,The thread often unlocks the corresponding mutex and waits for the condition to change.. Once another thread changes the condition variable, it will notify the corresponding condition variable to wake up one or more threads that are blocked by this condition variable. These threads will re-lock the mutex and re-test whether the conditions are met. In general, condition variables are used for line-to-line synchronization.
The condition variable structure is pthread_cond_t.
The simplest example:

pthread_cond_t cond;pthread_cond_init(&cond, NULL);pthread_cond_wait(&cond, &mutex);    ...pthread_cond_signal(&cond);

The thread that calls pthread_cond_wait will enter the waiting queue in the calling order. When a signal is generated, the thread that first enters the blocked queue will be awakened first. Conditional variables look similar in some ways.
As mentioned above, the condition variable makes up for the deficiency of the mutex lock.
In the examples of producers and consumers listed above, we add consumers (and assume that the buffer zone can tolerate multiple messages). For example, if three consumer threads use mutex, then all three threads need to constantly check whether there is any message in the buffer zone and take it away. This is undoubtedly a great waste of resources. If we use conditional variables, all three consumer threads can rest assured that there is a message in the buffer zone, and the consumer will receive the notification, then it will be enough to receive the message.

# Include <stdio. h> # include <stdlib. h> # include <pthread. h> # include <sys/time. h> static char buff [50]; pthread_mutex_t mutex; pthread_mutex_t cond_mutex; pthread_cond_t cond; void consumeItem (char * buff) {printf ("consumer item \ n ");} void produceItem (char * buff) {printf ("produce item \ n");} void * consumer (void * param) {int t = * (int *) param; while (1) {pthread_cond_wait (& cond, & cond_mutex); pthread_mutex_lock (& mutex); printf ("% d:", t); consumeItem (buff ); pthread_mutex_unlock (& mutex);} return NULL;} void * producer (void * param) {while (1) {pthread_mutex_lock (& mutex); produceItem (buff ); pthread_mutex_unlock (& mutex); pthread_cond_signal (& cond); sleep (1);} return NULL;} int main () {pthread_t tid_c, tid_p, tid_c2, tid_c3; void * retval; pthread_mutex_init (& mutex, NULL); pthread_mutex_init (& cond_mutex, NULL); pthread_cond_t cond; pthread_cond_init (& cond, NULL); int p [3] = {1, 2, 3}; // specifies the thread pthread_create (& tid_p, NULL, producer, NULL); pthread_create (& tid_c, NULL, consumer, & p [0]); pthread_create (& tid_c2, NULL, consumer, & p [1]); pthread_create (& tid_c3, NULL, consumer, & p [2]); pthread_join (tid_p, & retval ); pthread_join (tid_c, & retval); pthread_join (tid_c2, & retval); pthread_join (tid_c3, & retval); return 0 ;}

It should be noted that the condition variable only serves to block and wake up the thread. The user still needs to give the specific judgment condition, such as the number of messages in the buffer zone.
Other functions related to conditional variables include:
/* Destroy the condition variable cond */
Int pthread_cond_destroy (pthread_cond_t * cond );
/* Wake up all threads waiting for the condition variable cond */
Int pthread_cond_broadcast (pthread_cond_t * cond );

/* Wait for the condition variable until it times out */
Int pthread_cond_timedwait (pthread_cond_t * cond,
Pthread_mutex_t * mutex,
Const struct timespec * abstime );
/* Initialize the condition variable attribute attr */
Int pthread_condattr_init (pthread_condattr_t * attr );
/* Destroy condition variable attributes */
Int pthread_condattr_destroy (pthread_condattr_t * attr)

/* Process sharing flag for reading the condition variable attribute attr */
Int pthread_condattr_getpshared (const pthread_condattr_t *
Attr,
Int * pshared );

/* Update the process sharing flag of the condition variable attribute attr */
Int pthread_condattr_setpshared (pthread_condattr_t * attr,
Int pshared );

In general, condition variables are used for synchronization between threads.

● Semaphore

Semaphores are essentially non-negative integer counters used to control access to public resources. When public resources increase, the sem_post () function is called to increase the semaphore.
Public resources can be used only when the signal value is greater than 0. after use, the sem_wait () function reduces semaphores. Functions sem_trywait () and functions
Pthread _ mutex_trylock () plays the same role. It is a non-blocking version of The sem_wait () function.

Next we will introduce some functions related to semaphores one by one, which are defined in the header file/usr/include/semaphore. h.
The data type of the semaphore is sem_t, which is essentially a long integer. The sem_init () function is used to initialize a semaphore. Its prototype is:
Extern int sem_init _ P (sem_t * _ sem, int _ pshared, unsigned int _ value ));
Sem is a pointer to the semaphore structure. If pshared is not 0, the semaphore is shared among processes. Otherwise, it can only be shared among all threads of the current process. value indicates the initial value of the semaphore.
The sem_post (sem_t * sem) function is used to increase the semaphore value. When a thread is blocked on this semaphore, calling this function will make one of the threads not blocked. The selection mechanism is also determined by the thread scheduling policy.
The sem_wait (sem_t * sem) function is used to block the current thread until the semaphores sem value is greater than 0. After blocking is removed, the sem value is reduced by one, indicating that the public resources are reduced after use. The sem_trywait (sem_t * sem) function is a non-blocking version of The sem_wait () function, which directly reduces the semaphores sem value by one.
The sem_destroy (sem_t * sem) function is used to release semaphores.

In the above producer and consumer example, we assume that the buffer zone can hold up to 10 messages. Use semaphores to implement the following:

# Include <stdio. h> # include <stdlib. h> # include <pthread. h> # include <semaphore. h> static char buff [50]; pthread_mutex_t mutex; pthread_mutex_t cond_mutex; pthread_cond_t cond; sem_t msg_cnt; // number of messages in the buffer zone sem_t space_cnt; // buffer idle number void consumeItem (char * buff) {printf ("consumer item \ n");} void produceItem (char * buff) {printf ("produce item \ n");} void * consumer (void * param) {while (1) {sem_wait (& msg_cnt); pthread_mutex_lock (& mutex ); consumeItem (buff); pthread_mutex_unlock (& mutex); sem_post (& space_cnt);} return NULL;} void * producer (void * param) {while (1) {sem_wait (& space_cnt); pthread_mutex_lock (& mutex); produceItem (buff); pthread_mutex_unlock (& mutex); sem_post (& msg_cnt);} return NULL;} int main () {pthread_t tid_c, tid_p; void * retval; pthread_mutex_init (& mutex, NULL); consume (& cond_mutex, NULL); pthread_cond_t cond; pthread_cond_init (& cond, NULL ); sem_init (& msg_cnt, 0, 0); // No message sem_init (& space_cnt, 0, 10) in the initial buffer; // The initial buffer can hold 10 messages pthread_create (& tid_p, NULL, producer, NULL); pthread_create (& tid_c, NULL, consumer, NULL); pthread_join (tid_p, & retval); pthread_join (tid_c, & retval); return 0 ;}

 

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.