producer-consumer problem with pthreads producer-consumer problem with pthreads multithreading multithreading

producer-consumer problem with pthreads


Both the consumer and producer does a sleep(rand()) which will sleep for a random number of seconds between 0 and MAX_INT, in the example you give the main thread will terminate after 10 seconds. If the rand() value of the producers are above 10 they will never have the chance produce anything.


You should start by using an array of threads...

pthread_t tid[argarray[1] + argarray[2]];for(c1 = 0; c1 < argarray[1]; c1++){    pthread_create(&tid[c1], &attr, producer, NULL);    printf("Creating producer #%d\n", c1); }for(c1 = 0; c1 < argarray[2]; c1++){    pthread_create(&tid[c1 + argarray[1]], &attr, consumer, NULL);    printf("Creating consumer #%d\n", c1); }

There may be other problems but this is the first one I see ...


You should not directly call exit at the end of your main function. You should first call pthread_join for the threads you created at the end, to keep the main thread alive until the other threads die.