![]() |
![]() |
![]() |
Lock mutex
#include <pthread.h> int pthread_mutex_lock( pthread_mutex_t* mutex );
libc
The pthread_mutex_lock() function locks the mutex object referenced by mutex. If the mutex is already locked, then the calling thread blocks until it has acquired the mutex. When the function returns the mutex object is locked and owned by the calling thread.
If the mutex is statically initialized to allow recursive behavior (using PTHREAD_RMUTEX_INITIALIZER), or the mutex attributes are changed before pthread_mutexattr_init() using pthread_mutexattr_setrecursive() to PTHREAD_RECURSIVE_ALLOW, a call to pthread_mutex_lock() while you own the mutex succeeds. In this case, you must call pthread_mutex_unlock() for each corresponding call to lock the mutex. The default POSIX behavior doesn't allow recursive mutexes and returns EDEADLK.
If a signal is delivered to a thread waiting for a mutex, upon return from the signal handler, the thread resumes waiting for the mutex.
This example shows how a mutex can be used to synchronize access to a shared variable. In this example, function1() and function2() both attempt to access and modify the global variable count. Either thread could be interrupted between modifying count and assigning its value to the local tmp variable. Locking mutex prevents this from happening; if one thread has mutex locked, the other thread waits until it's unlocked before continuing.
#include <stdio.h> #include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int count = 0; void* function1( void* arg ) { int tmp = 0; while( 1 ) { pthread_mutex_lock( &mutex ); tmp = count++; pthread_mutex_unlock( &mutex ); printf( "Count is %d\n", tmp ); /* snooze for 1 second */ sleep( 1 ); } return 0; } void* function2( void* arg ) { int tmp = 0; while( 1 ) { pthread_mutex_lock( &mutex ); tmp = count--; pthread_mutex_unlock( &mutex ); printf( "** Count is %d\n", tmp ); /* snooze for 2 seconds */ sleep( 2 ); } return 0; } int main( void ) { pthread_create( NULL, NULL, &function1, NULL ); pthread_create( NULL, NULL, &function2, NULL ); /* Let the threads run for 60 seconds. */ sleep( 60 ); return 0; }
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |
pthread_mutexattr_init(), pthread_mutexattr_setrecursive(), pthread_mutex_trylock(), pthread_mutex_unlock(), SyncMutexLock()
![]() |
![]() |
![]() |