pthread_mutex_lock, pthread_mutex_trylock |
Prototype: |
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
|
General Description: |
Lock or try to lock a semaphore for entering a critical section. The parameter is simply a variable that acts like a reservation ticket. If another thread tries to lock a reserved spot, it blocks until the reserving thread releases the semaphore. |
Return Value: |
The call returns a zero on success and nonzero on error. You can find the exact code in errno. |
Parameters |
mutex |
The semaphore variable. |
Possible Errors |
EINVAL |
The mutex has not been properly initialized. |
EDEADLK |
[try_lock] The calling thread has already locked the mutex (error checking mutexes only). |
EBUSY |
[lock] The calling thread can't acquire, because it is currently locked. |
Examples |
pthread_mutex_t mutex = fastmutex;
...
if ( pthread_mutex_lock(&mutex) == 0 )
{
/**** work on critical data ****/
pthread_mutex_unlock(&mutex);
}
|
pthread_mutex_t mutex = fastmutex;
...
/*---Do other processing while waiting for semaphore---*/
while ( pthread_mutex_trylock(&mutex) != 0 && errno == EBUSY )
{
/**** Work on something else while waiting ****/
}
/*---Got the semaphore! Now work on the critical section---*/
if ( errno != ENOERROR )
{
/**** work on critical data ****/
pthread_mutex_unlock(&mutex);
}
|