Linux multithreaded Programming-Mutual exclusion lock

Source: Internet
Author: User

Mutual exclusion Lock

In multithreaded programming, (multithreaded programming) can be used to protect critical sections of code by using mutexes (also known as mutexes) to ensure exclusive access, which is somewhat like a binary semaphore. The POSIX mutex correlation function has the following 5 main characters:

#include <pthread.h>int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr); int Pthread_mutex_destroy (pthread_mutex_t *mutex); 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 first parameter of these functions the mutex points to the target mutex to be manipulated, returns 0 on success, and returns an error code

L pthread_mutex_init is used to initialize the mutex, mutexattr is used to specify the property of the mutex, and if NULL, represents the default property. In addition to using this function to initialize the mutex, it can also be initialized as follows: pthread_mutex_t mutex = Pthread_mutex_initializer;

L Pthread_mutex_destroy is used to destroy the mutex to free up the occupied kernel resources, destroying an already locked mutex will result in unpredictable consequences

L Pthread_mutex_lock A mutex lock with atomic operation. If the target mutex is already locked, then the pthread_mutex_lock is blocked until the mutex is unlocked by the exclusive lock

L pthread_mutex_trylock and Pthread_mutex_lock are similar, but it always returns immediately, regardless of whether the mutex being manipulated is locked, is a non-blocking version of Pthread_mutex_lock. Pthread_mutex_trylock the lock operation when the target mutex is not locking, otherwise the EBUSY error code will be returned. Note: The Pthread_mutex_lock and Pthread_mutex_trylock discussed here are for normal locks, and for other types of locks, these two lock functions behave differently.

L Pthread_mutex_unlock an atomic operation to unlock a mutex. If another thread is waiting for the mutex at this point, one of those threads will get it


Mutual Exclusion Lock Example program :

#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define ERR_SYS (msg) do {perror (msg); exit (-1); } while (0) #define ERR_EXIT (msg) does {fprintf (stderr, msg); exit ( -1);} while (0) int glab = 1;void *r1 (void *arg) {Pthread_mu tex_t* Mutex = (pthread_mutex_t *) arg;static int cnt = 10;while (cnt--) {pthread_mutex_lock (mutex); glab++;p rintf ("I AM in R 1. CNT =%d\n ", Glab);p Thread_mutex_unlock (mutex); sleep (1);} Return "R1 over";} void *r2 (void *arg) {pthread_mutex_t* mutex = (pthread_mutex_t *) arg;static int cnt = 10;while (cnt--) {Pthread_mutex_lock ( Mutex); glab++;p rintf ("I am in R2. CNT =%d\n ", Glab);p Thread_mutex_unlock (mutex); sleep (1);} Return "R2 over";} int main (void) {pthread_mutex_t mutex;pthread_t t1, t2;char* p1 = null;char* P2 = null;if (Pthread_mutex_init (&mutex, N ULL) < 0) Err_sys ("Sem_init error");p thread_create (&t1, NULL, R1, &mutex);p thread_create (&t2, NULL, R2, & Amp;mutex);p thread_join (t1, (void * *) &p1);p Thread_join (T2, (void * *) &p2);p threAd_mutex_destroy (&mutex);p rintf ("S1:%s\n", p1);p rintf ("S2:%s\n", p2); return 0;} 


Mutex properties

The pthread_mutexattr_t structure defines a complete set of mutex properties. Line libraries provides a series of functions to manipulate pthread_mutexattr_t type variables so that we can get and set the mutex properties. Here are some of the main functions:

#include <pthread.h>int Pthread_mutexattr_destroy (pthread_mutexattr_t *attr); int Pthread_mutexattr_init ( pthread_mutexattr_t *attr); int pthread_mutexattr_getpshared (const pthread_mutexattr_t *restrict attr, int *restrict pshared); int pthread_mutexattr_setpshared (pthread_mutexattr_t *attr, int pshared); int Pthread_mutexattr_gettype ( Const pthread_mutexattr_t *restrict attr, int *restrict type); int Pthread_mutexattr_settype (pthread_mutexattr_t *attr, int type);

Two common properties of mutexes: Pshared and type

The Mutex property pshared Specifies whether the mutex is allowed to be shared across processes, with an optional value of two:

L pthread_process_shared. Mutual exclusion locks can be shared across processes.

L pthread_process_private. Mutexes can only be shared by threads that are part of the same process as the lock's initialization thread.

The Mutex property type specifies the kind of mutex. Linux supports the following 4 types of mutex locks:

L pthread_mutex_normal, normal lock. This is the default type of mutex. When a thread locks a normal lock, the rest of the request's thread forms a wait queue and obtains it by priority after it is unlocked. This type of lock guarantees the fairness of resource allocation. But this kind of lock can also easily cause problems: if a thread locks a lock on a normal lock again, it will trigger a deadlock, unlock a normal lock that has been Cheng by another thread, or unlock an unlocked normal lock to cause unintended consequences.

L Pthread_mutex_errorcheck, check the wrong lock. If a thread is locked again with a locked check lock, the lock operation returns EDEADLK. To unlock a Cheng that has been locked by his thread, or to unlock a lock that has been unlocked again, the wrong lock returns EPERM.

L pthream_mutex_recursive, nested lock. This lock allows a thread to lock a lock without a deadlock before releasing it. However, if the other thread is to obtain this lock, the owner of the current lock must perform the appropriate number of unlocking operations. Unlocking a nested lock that has been locked by another thread's yoke, or unlocking a nested lock that has been unlocked again, the unlock operation returns EPERM.

L pthread_mutex_default, default lock. A thread can cause unintended consequences if it locks a default lock that has been locked again, or unlocks a default lock that has been Cheng by another line, or unlocks a default lock that has already been unlocked.


example of using a nested lock (pthream_mutex_recursive) program

#include <stdio.h> #include <stdlib.h> #include <pthread.h>int a = 1;int B = 1;pthread_mutex_t Mutex; void *pthread1 (void *arg) {while (1) {if (Pthread_mutex_lock (&mutex)! = 0) {printf ("1 error\n"); continue;} if (Pthread_mutex_lock (&mutex)! = 0)/* Call 2 lock Operation */{printf ("1 error\n") at this time; continue;} A++;b++;if (A! = b) printf ("Pthread1:%d,%d\n", A, B), elseprintf ("11\n");p Thread_mutex_unlock (&mutex);p Thread_ Mutex_unlock (&mutex); sleep (1);}} void *pthread2 (void *arg) {while (1) {if (Pthread_mutex_lock (&mutex)! = 0) {printf ("2 error\n"); continue;} A++;b++;if (A! = b) printf ("Pthread2:%d,%d\n", A, B), elseprintf ("------------\ n");p Thread_mutex_unlock (&mutex) ; sleep (1);}} int main (void) {pthread_t tid1, tid2;pthread_mutexattr_t attr;pthread_mutexattr_init (&attr);p thread_mutexattr_ Settype (&attr, pthread_mutex_recursive);p thread_mutex_init (&mutex, &attr);p thread_create (&AMP;TID1, NULL, PTHREAD1, NULL);p thread_create (&tid2, NULL, PTHREAD2, NULL);p Thread_joiN (tid1, NULL);p thread_join (TID2, NULL);p Thread_mutex_destroy (&mutex); return 0;} 

Reference

1,"Linux high-performance server Programming," chapter 14th multithreaded Programming/mutual exclusion lock

2. Linux multithreaded programming

3, Linux multi-threaded programming-signal volume

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux multithreaded Programming-Mutual exclusion lock

Related Article

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.