can-mohan 0 Junior Poster

Hi All,

I am new to thread programing. In below code snippet inside producer thread if return NULL statement is removed i observed programme is hanging. Usually after execution of pthread_cond_signal(&cond); i believe i am out of this thread and consumer thread already have taken proper exit after execution of statement ** if(item==0) return NULL**. Can anybody through some light on this as i am getting desire output but programme is hangning and only return NULL statement in prodcuer thread is the soultion.

 #include <pthread.h>
 #include <stdio.h>

    pthread_mutex_t mutex;
    pthread_cond_t cond;

    int buffer[100];

    int loops = 5;
    int length = 0;

    void *producer(void *arg) {
        int i=0;

        for (;;)
         {
            pthread_mutex_lock(&mutex);
            if(i==5) //Max_buffer 5
            {
            pthread_cond_signal(&cond);
            pthread_mutex_unlock(&mutex);
            return NULL;// if this stament is removed then programme will hang.
            }
            else
             {

            buffer[length++] = i++;
            printf("producer length %d\n", length);
            pthread_mutex_unlock(&mutex);

            }

    }
    }

    void *consumer(void *arg) {
        int i=0;

        for (;;) {
            pthread_mutex_lock(&mutex);
            if(length == 0) {
                printf(" consumer waiting...\n");
                pthread_cond_wait(&cond, &mutex);
            }
            int item = buffer[--length];
            printf("Consumer %d\n", item);
           pthread_mutex_unlock(&mutex);
             if(item==0) return NULL;
        }
    }

    int main(int argc, char *argv[])
    {

        pthread_mutex_init(&mutex, 0);
        pthread_cond_init(&cond, 0);
        pthread_t pThread, cThread;
        pthread_create(&cThread, 0, consumer, 0);
        pthread_create(&pThread, 0, producer, 0);
        pthread_join(cThread, NULL);
        pthread_join(pThread, NULL);
        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&cond);
        return 0;   
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.