/* * ImplementaĆ§Ć£o de locks recursivos. */ #include "lr.h" int rec_mutex_init(rec_mutex_t* rec_m) { pthread_mutex_init(&rec_m->lock, NULL); pthread_cond_init(&rec_m->cond, NULL); return 0; } int rec_mutex_lock(rec_mutex_t* rec_m) { pthread_mutex_lock(&rec_m->lock); if (rec_m->c == 0) { /* Lock livre */ rec_m->c = 1; rec_m->thr = pthread_self(); } else /* Mesma thread */ if (pthread_equal(rec_m->thr, pthread_self())) rec_m->c++; else { /* Thread deve esperar */ while (rec_m->c != 0) pthread_cond_wait(&rec_m->cond, &rec_m->lock); rec_m->thr = pthread_self(); rec_m->c = 1; } pthread_mutex_unlock(&rec_m->lock); return 0; } int rec_mutex_unlock(rec_mutex_t* rec_m) { pthread_mutex_lock(&rec_m->lock); rec_m->c--; if (rec_m->c == 0) pthread_cond_signal(&rec_m->cond); pthread_mutex_unlock(&rec_m->lock); return 0; } int rec_mutex_destroy(rec_mutex_t* rec_m) { return 0; }