Producer Consumer Problem

Problem Statement

The producer-consumer problem is a classic synchronization problem in concurrent programming. It involves two types of processes or threads: producers and consumers. Producers generate data items, and consumers consume or process these data items. The challenge is to coordinate the activities of producers and consumers in a way that ensures data integrity and avoids issues such as race conditions, data corruption, and deadlock.

Problem Statement:

  1. There is a shared buffer or queue that can hold a limited number of items.

  2. Producers generate items and add them to the buffer.

  3. Consumers remove items from the buffer and process them.

  4. Producers and consumers must access the buffer in a mutually exclusive manner to avoid race conditions.

  5. Producers must wait if the buffer is full, and consumers must wait if the buffer is empty.

Solution

  1. mutex : binary semaphore used in to acquire lock on buffer.

  2. empty : a counting semaphore to track empty slots { initially n }.

  3. full : counting semaphore tracks the slots filled { initially 0 }.

Producer :

do {
    
    wait( empty ); // wait until empty > 0 then , empty->val--
    wait( mutex ); // wait until we don't lock on buffer
    
    // Start critical section
    producer()
    // End Critical Section
    
    signal( mutex ); // release lock on the buffer and notify all
    signal( full ); // increment the value of full , full->val++
    
} while ( True );

Consumer :

do {
    
    wait( full ); // wait until full > 0 then , full->val--
    wait( mutex ); // wait until we don't get lock on buffer
    
    // Start critical section
    consumer()
    // End Critical Section
    
    signal( mutex ); // release lock and notify all
    signal( empty ); // increment the empty value , empty->val++
    
} while ( True );

Last updated