Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.4a |
both | POSIX(ON) |
#define _OPEN_THREADS
#include <pthread.h>
int pthread_mutex_trylock(pthread_mutex_t *mutex);
#define _UNIX03_THREADS
#include <pthread.h>
int pthread_mutex_trylock(pthread_mutex_t *mutex);
Locks a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. If pthread_mutex_trylock() is locked, it returns immediately.
For recursive mutexes, pthread_mutex_trylock() will effectively add to the count of the number of times pthread_mutex_unlock() must be called by the thread to release the mutex. (That is, it has the same behavior as a pthread_mutex_lock().)
If successful, pthread_mutex_trylock() returns 0.
Special behavior for Single UNIX Specification, Version 3: If unsuccessful, pthread_mutex_trylock() returns an error number to indicate the error.
⁄* CELEBP40 *⁄
#define _OPEN_THREADS
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
pthread_mutex_t mutex;
void *thread(void *arg) {
if (pthread_mutex_trylock(&mutex) != 0)
if (errno == EBUSY)
puts("thread was denied access to the mutex");
else {
perror("pthread_mutex_trylock() error");
exit(1);
}
else puts("thread was granted the mutex");
}
main() {
pthread_t thid;
if (pthread_mutex_init(&mutex, NULL) != 0) {
perror("pthread_mutex_init() error");
exit(2);
}
if (pthread_create(&thid, NULL, thread, NULL) != 0) {
perror("pthread_create() error");
exit(3);
}
if (pthread_mutex_trylock(&mutex) != 0)
if (errno == EBUSY)
puts("IPT was denied access to the mutex");
else {
perror("pthread_mutex_trylock() error");
exit(4);
}
else puts("IPT was granted the mutex");
if (pthread_join(thid, NULL) != 0) {
perror("pthread_mutex_trylock() error");
exit(5);
}
}
IPT was granted the mutex
thread was denied access to the mutex