Subj : Semaphores and pthreads To : comp.programming.threads From : Paolo Date : Sun Jan 09 2005 04:06 pm Hello! First of all: Happy New Year =) Then my question: I have a program that can be imagined as a "producers consumer" program. it is written in C, and it uses pthreads. 2 threads produce resources and one cosumes them. to syncronize them i used a semaphore (sem_t) and a mutex imagine that the life of a producer is: foo=produce(); ptrehad_mutex_lock(&mutex); enqueue(foo); pthread_mutex_unlock(&mutex); sem_post(&semaphore); and the life of the consumer is: sem_wait(&semaphore); ptrehad_mutex_lock(&mutex); bar=dequeue(); check_if_the_queue_is_empty(&bar); pthread_mutex_unlock(&mutex); process_the_resource(bar); now, i have the problem that seldom it happens that inside the consumer i wake up from the sem_wait(&semaphore), but i found the queue as empty. So i tried to define these macros, with the aid of a 2nd mutex, namely mutex2: MY_P() { sem_wait(&semaphore);\ pthread_mutex_lock(&mutex2);\ semcounter--;\ pthread_mutex_unlock(&mutex2);\ } MY_V() { pthread_mutex_lock(&mutex2);\ sem_post(&semaphore);\ semcounter++;\ pthread_mutex_unlock(&mutex2);\ } I use them in place of sem_wait(&semaphore) and sem_post(&semaphore). When the disaster happen (that is i wake up but have empty queue), i said to the function check_if_the_queue_is_empty() to do: int temp,val; [...] pthread_mutex_lock(&mutex2); val=sem_getvalue(&semaphore,&temp); val=semcounter; printf("SEMCOUNTER:%d SEM_VALUE:%d\n",val,temp); pthread_mutex_unlock(&semaforo); [...] and i obtain that the SEM_VALUE is correctly 0 (else i can't resume from sem_wait()), but the SEMCOUNTER is -1!!!!! that is i have a deficit in the P()/V() balance. this means that either someone other than my threads do a V() or that when i do sem_wait() and the sem_value is 0, the function does not decrement the semaphore counter.. I honestly find this a pretty strange behaviour. and i don't know how to fix it, becouse i'm sure that i do sem_wait() and sem_post() when i should, since my own counter (semcounter) cointains the right #V() - #P() value. Any suggestion will be appreciated Thank you and excuse me for this long message :-) Paolo .