Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.4a |
both | POSIX(ON) |
#define _OPEN_THREADS
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mutex);
#define _UNIX03_THREADS
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mutex);
Locks a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.
When the mutex has the attribute of recursive, the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then a count is incremented and no waiting thread is posted. The owning thread must call pthread_mutex_unlock() the same number of times to decrement the count to zero.
If successful, pthread_mutex_lock() returns 0.
Special behavior for Single UNIX Specification, Version 3: If unsuccessful, pthread_mutex_lock() returns an error number to indicate the error.
If the _OPEN_SYS_MUTEX_EXT feature switch is set, all shared (extended) mutex locks are released when the thread ends, whether normally or abnormally. If the thread ends normally (i.e. pthread_exit() or pthread_cancel()), the first waiter of the mutex lock will be resumed. If the thread ends abnormally, the processes of the mutex waiters for this mutex lock will be terminated.
⁄* CELEBP38 *⁄
#ifndef _OPEN_THREADS
#define _OPEN_THREADS
#endif
#include <pthread.h>
#include <stdio.h>
main() {
pthread_mutex_t mut;
if (pthread_mutex_init(&mut, NULL) != 0) {
perror("mutex_lock");
exit(1);
}
if (pthread_mutex_lock(&mut) != 0) {
perror("mutex_lock");
exit(2);
}
puts("the mutex has been locked");
exit(0);
}