Why do I need a mutex?
In a multitasking operating system, multiple tasks that run concurrently may require the same resource to be used. This process is a bit like, in the company department, I am using the printer while printing things (not yet printed), others happen to use the printer at the moment to print things, if you do not do any processing, the printed things must be out of the confusion.
Below we use the program to simulate this process, the thread needs to print "Hello", thread two need to print "world", without any processing, the printed content will be confused:
#include <stdio.h> #include <pthread.h> #include <unistd.h>//printer void printer (char *str) {while (*str! = ' + ') {Putchar (*STR); fflush (stdout); Str++;sleep (1);} printf ("\ n"); }//thread one void *thread_fun_1 (void *arg) {char *str = "Hello";p rinter (str);//print}//thread two void *thread_fun_2 (void *arg) {char *str = "World";p rinter (str); Print}int main (void) {pthread_t tid1, tid2;//create 2 threads pthread_create (&TID1, NULL, thread_fun_1, NULL);p thread_create ( &tid2, NULL, thread_fun_2, NULL),//wait for thread to end, reclaim its resource pthread_join (TID1, NULL);p thread_join (TID2, NULL); return 0;}
The results of the operation are as follows:
In fact, the printer has to do processing, I am printing when others are not allowed to print, only after I print the end of the people will be allowed to print. This process is a bit like, put the printer in a room, give the room a lock, the lock is open by default. When A needs to be printed, he comes first to check if the lock is locked or not, then go in and lock it in the room to print. At this point, just B also need to print, B Also check the lock, found that the lock is locked, he is waiting outside the door. And when A print is finished, he unlocks it, and B then goes in to lock the print.
and the online thread also has such a lock-mutex (mutex), mutexes are a simple locking method to control access to shared resources, with only two states, lock and Unlock (unlock).
The operation flow of the mutex is as follows:
1) Lock the mutex before accessing the critical area of the shared resource.
2) Release the lock on the mutex when the access is complete.
3) When the mutex is locked, any other thread that attempts to lock the mutex again will be blocked until the lock is released.
the data type of the mutex is: pthread_mutex_t .
Mutual exclusion Lock basic operation
The following function requires a header file:
#include <pthread.h>
1) Initialize Mutex lock
int Pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
Function:
Initializes a mutex.
Parameters:
Mutex: the exclusive lock address. The type is pthread_mutex_t.
attr: Sets the property of the mutex, usually with the default property, to set attr to NULL.
You can use a macro pthread_mutex_initializer to statically initialize a mutex, such as:
pthread_mutex_t mutex = Pthread_mutex_initializer;
This method is equivalent to using the NULL specified attr parameter to call pthread_mutex_init () to complete dynamic initialization, except that pthread_mutex_ INITIALIZER macros do not check for errors.
return value:
Success: 0, the lock that was successfully applied is turned on by default.
Failure: not 0 error code
2) lock
int Pthread_mutex_lock (pthread_mutex_t *mutex);
Function:
For a mutex lock, if the mutex is locked, the caller blocks until the mutex is unlocked and then locked.
Parameters:
Mutex: the exclusive lock address.
return value:
Success: 0
Failure: not 0 error code
int Pthread_mutex_trylock (pthread_mutex_t *mutex);
When this function is called, if the mutex is unlocked, it is locked, returns 0, and if the mutex is locked, the function returns the failure directly, that is, ebusy.
3) Unlocking
int Pthread_mutex_unlock (pthread_mutex_t * mutex);
Function:
Unlocks the specified mutex lock.
Parameters:
Mutex : The exclusive lock address.
return value:
Success: 0
Failure: not 0 error code
4) Destroy the mutex lock
int Pthread_mutex_destroy (pthread_mutex_t *mutex);
Function:
Destroys one of the specified mutex locks. After the mutex is used, the mutex must be destroyed to release the resource.
Parameters:
Mutex : The exclusive lock address.
return value:
Success: 0
Failure: not 0 error code
application examples of mutual exclusion lock
We refine the above example with a mutex, the sample code is as follows:
#include <stdio.h> #include <pthread.h> #include <unistd.h>pthread_mutex_t mutexes; Mutex//printer void printer (char *str) {pthread_mutex_lock (&mutex);//Lock while (*str!= ' n ') {Putchar (*STR); Fflush ( STDOUT); Str++;sleep (1);} printf ("\ n"); Pthread_mutex_unlock (&mutex); Unlock}//thread one void *thread_fun_1 (void *arg) {char *str = "Hello";p rinter (str);//print}//thread two void *thread_fun_2 (void *arg) {Char *STR = "World";p rinter (str); Print}int main (void) {pthread_t tid1, Tid2;pthread_mutex_init (&mutex, NULL);//Initialize Mutex//create 2 threads pthread_create (& TID1, NULL, thread_fun_1, NULL);p thread_create (&tid2, NULL, thread_fun_2, NULL),//wait for thread to end, reclaim its resources pthread_join (TID1, NULL);p Thread_join (Tid2, NULL); Pthread_mutex_destroy (&mutex); Destroy mutex return 0;}
The results of the operation are as follows:
For this tutorial sample code download please click here.
Linux system Programming--thread synchronization and mutual exclusion: mutual exclusion lock