Subj : Re: pthread_cond to create sema? To : comp.programming.threads From : Giancarlo Niccolai Date : Wed Jan 19 2005 07:46 pm 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). 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. Bests, Giancarlo. .