Tag Archives: Multithreading

Producer/consumer using pthreads

Here I present a C-program to demonstrate the use of pthreads to solve the classical producer/consumer problem. The following (self-explaining) program makes use of pthread’s mutex & condition APIs to achieve synchronization between producer & consumer threads. The program implements a simplified version of the original problem : the producer increments (produces) an integer, a shared resource, while the consumer prints (consumes) it.

Output:

Consumer : "Hello I am consumer #140317330908928. Ready to consume numbers now"
Producer : "Hello I am producer #140317322516224. Ready to produce numbers now"
Producer : 1
Consumer : 1
Producer : 2
Consumer : 2
Producer : 3
Consumer : 3
Producer : 4
Consumer : 4
Producer : 5
Consumer : 5
Producer : 6
Consumer : 6
Producer : 7
Consumer : 7
Producer : 8
Consumer : 8
Producer : 9
Consumer : 9
Producer : 10
Producer done.. !!
Consumer : 10
Consumer done.. !!
Done..