xxx7xxxx
xxx7xxxx

Reputation: 824

Producer-consumer , Why not implement it with ONE semaphore?

Using My idea which take only one semaphore(except mutex)

    n = 10
    mutex = 1

 producer:   //This is producer
    P(mutex)
    V(n)
    V(mutex)   

 cosumer:    //This is consumer
    P(mutex)
    P(n)
    V(mutex)

Below using traditional two semaphore to implement it.

    n = 10
    empty = 0
    mutex = 1

 producer:   //This is producer
    P(empty)
    P(mutex)
    produce();
    V(mutex)
    V(n)

 consumer:    //This is consumer
    P(n)
    p(mutex)
    consume()
    V(mutex)
    V(empty)

Upvotes: 2

Views: 2361

Answers (1)

A. I. Breveleri
A. I. Breveleri

Reputation: 767

In the ring-buffer producer-consumer pattern, the producer puts items into a buffer of limited size, and the consumer removes items from that buffer.

The key to comprehending the pattern is to understand that the producer is also a consumer -- it consumes empty buffer slots.

The purpose of a semaphore is to control critical access to a counted resource. Since items in the buffer are a counted resource and empty buffer slots are also a counted resource, two semaphores are necessary.

A redundancy appears, because the two semaphore counts are not independent. Their sum remains constant, and is equal to the buffer size. Also, the two thread queues are not independent. At any moment, only one of the semaphores will hold any suspended threads, because there will never be producers and consumers waiting at the same time. However, the redundancy is not complete enough to allow the elimination of one of the semaphores.

The construction you suggest, if I understand you, will fail because the producer will not stop when the buffer is full. Also, if the consumer waits on an empty buffer, it blocks the the producer from ever reaching its 'V(n)' operation.

The redundancy does suggest more efficient synchronizing might be possible for the producer-consumer pair, and indeed many others have been suggested. See in particular the 'monitor' technique.

Upvotes: 2

Related Questions