標準/拡張機能 | C/C++ | 依存項目 |
---|---|---|
POSIX.4a |
両方 | 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);
mutex を識別する mutex オブジェクトをロックします。mutex は、共用リソースを保護する場合に使用されます。 pthread_mutex_trylock() はロックされると、即時に戻ります。
再帰的 mutex の場合、pthread_mutex_trylock() は、mutex を解放するためにスレッドが pthread_mutex_trylock() を呼び出す 必要がある回数のカウントにこれを効果的に追加します。(つまり、pthread_mutex_lock() と同じ動作をとります。)
正常に実行された場合、pthread_mutex_trylock() は 0 を戻します。
Single UNIX Specification、バージョン 3 の特殊な動作: 正常に実行されなかった場合、pthread_mutex_trylock() はエラーを示すエラー番号を戻します。
⁄* 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