/* * Implementação de locks recursivos. */ #include "lr.h" int rec_mutex_init(rec_mutex_t* rec_m) { pthread_mutex_init(&rec_m->lock_var,0); pthread_cond_init(&rec_m->cond,0); rec_m->c = 0; return 0; } int rec_mutex_lock(rec_mutex_t* rec_m) { pthread_mutex_lock(&rec_m->lock_var); if (rec_m->c == 0) { rec_m->thr = pthread_self(); rec_m->c = 1; } else if (pthread_equal(rec_m->thr, pthread_self())) rec_m->c++; else { while (rec_m->c != 0) pthread_cond_wait(&rec_m->cond, &rec_m->lock_var); rec_m->thr = pthread_self(); rec_m->c = 1; } pthread_mutex_unlock(&rec_m->lock_var); return 0; } int rec_mutex_unlock(rec_mutex_t* rec_m) { pthread_mutex_lock(&rec_m->lock_var); rec_m->c--; if (rec_m->c == 0) pthread_cond_signal(&rec_m->cond); pthread_mutex_unlock(&rec_m->lock_var); return 0; } int rec_mutex_destroy(rec_mutex_t* rec_m) { if (rec_m->c > 0) return -1; pthread_mutex_destroy(&rec_m->lock_var); pthread_cond_destroy(&rec_m->cond); return 0; }