1. The mutual exclusion lock is introduced to ensure the integrity of shared data operations.
2. mutex lock is mainly used to protect critical resources.
3. Each critical resource is protected by a mutex. At any time, only one thread can access the resource.
4. The thread must obtain the mutex lock before accessing the critical resource. After the resource is accessed, the lock is released. If the lock cannot be obtained, the thread will be blocked until the lock is obtained.
Functions used
Pthread_mutex_init ();
Pthread_create ();
Pthread_join ();
Pthread_mutex_lock ();
Pthread_mutex_unlock ();
----------------------------------------------------------------------------------
Common. h
Bytes -----------------------------------------------------------------------------------
# Ifndef _ common_h
# DEFINE _ common_h
# Include <stdio. h>
# Include <stdlib. h>
# Include <pthread. h>
Extern void pthread_function1 (void * Arg );
Extern void pthread_function2 (void * Arg );
# Endif
Bytes -------------------------------------------------------------------------------------
Pthread_mutex.c
Bytes ---------------------------------------------------------------------------------------
# Include "common. H"
Pthread_mutex_t mutex = pthread_mutex_initializer;
Int gval;
Int I;
Int main (INT argc, char ** argv)
{
Pthread_t Th1, 22;
Pthread_mutex_init (& mutex, null );
Pthread_create (& Th1, null, (void *) pthread_function1, null );
Pthread_create (& 2nd, null, (void *) pthread_function2, null );
Pthread_join (Th1, null );
Pthread_join (2nd, null );
Return 0;
}
Void pthread_function1 (void * Arg)
{
For (I = 0; I <5; I ++)
{
Pthread_mutex_lock (& mutex );
Gval ++;
Pthread_mutex_unlock (& mutex );
Printf ("thread1 No. % d = % d/N", I, gval );
}
}
Void pthread_function2 (void * Arg)
{
For (I = 0; I <5; I ++)
{
Pthread_mutex_lock (& mutex );
Gval = gval + 2;
Pthread_mutex_unlock (& mutex );
Printf ("thread2 No. % d = % d/N", I, gval );
}
}
Bytes -----------------------------------------------------------------------------------
Result:
[Root @ localhost pthread mutex] #./s
Thread1 no.0 = 1
Thread1 No.1 = 2
Thread1 No. 2 = 3
Thread1 No. 3 = 4
Thread1 No. 4 = 5
Thread2 no.0 = 7
Thread2 No.1 = 9
Thread2 No. 2 = 11
Thread2 No. 3 = 13
Thread2 No. 4 = 15
The second thread function is executed only after the first thread function is finished.