Subj : Re: pthread_cond to create sema? To : comp.programming.threads From : Paolo Date : Thu Jan 20 2005 08:00 am Giancarlo Niccolai wrote: > Paolo wrote: >> >> Are these P() and V() correct if i want to implement >> semaphores p() and v() functions? >> >> messagecounter is a global int variable, >> semaforo is a mutex used only here >> sema is a cond variable >> >> >> >> #define P() {\ >> pthread_mutex_lock(&semaforo);\ >> while ( TW_messagecounter <= 0) {\ >> pthread_cond_wait(&sema, &semaforo);\ >> }\ >> messagecounter--;\ >> pthread_mutex_unlock(&semaforo);\ >> } >> >> #define V() {\ >> pthread_mutex_lock(&semaforo);\ >> messagecounter++;\ >> pthread_cond_signal(&sema);\ >> pthread_mutex_unlock(&semaforo);\ >> } >> >> Thank you! >> Paolo > Yes, but you can make it better by checking if there are waiting agents > before signaling and pushing the cleanup function before waiting (and > popping it after waiting). Do you think i could get a speed boost avoiding a signal for each V() with a new variable and a check on it? >Minimal cleanup is the pthread_unlock_mutex, so > that if your wait is killed by another thread, the mutex gets unlocked > before the agent is definitely stopped. How can i unlock the mutex if i'm killed, before i have to exit? with a signal handler? > Bests, > Giancarlo. Thank you! Paolo .