#include #include #include #include void * thr_routine(void *arg) { pthread_mutex_t *m = (pthread_mutex_t *)arg; int err; printf("thread %p: locking mutex...\n", pthread_self()); err = pthread_mutex_lock(m); if (err == EOWNERDEAD) { printf("thread %p: found owner is dead, try to fix it.\n", pthread_self()); int ret = pthread_mutex_consistent(m); printf("thread %p: pthread_mutex_consistent returns %d.\n", pthread_self(), ret); assert(pthread_mutex_unlock(m) == 0); printf("thread %p: unlocked mutex.\n", pthread_self()); printf("thread %p: trying to relock it.\n", pthread_self()); err = pthread_mutex_lock(m); if (err == 0) { printf("thread %p: relock success.\n", pthread_self()); assert(pthread_mutex_unlock(m) == 0); } else { pthread_mutex_unlock(m); } } else if (err == ENOTRECOVERABLE) { printf("thread %p: found owner is dead.\n", pthread_self()); } else { printf("thread %p: unknown error %d.\n", pthread_self(), err); } } int test1(void) { pthread_t td; pthread_mutex_t m; pthread_mutexattr_t ma; int ret; pthread_mutexattr_init(&ma); assert(pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST) == 0); assert(pthread_mutex_init(&m, &ma) == 0); pthread_mutexattr_destroy(&ma); assert(pthread_mutex_lock(&m) == 0); printf("thread %p: locked mutex.\n", pthread_self()); assert(pthread_create(&td, NULL, thr_routine, &m) == 0); sleep(1); printf("thread %p: exits without unlocking mutex.\n", pthread_self()); pthread_exit(0); } int main() { test1(); }