I am doing self-studying of operating systems. Tanenbaum in his book modern operating systems states an example where he explains how three semaphores (one of which is a mutex) coordinate a producer-comsumer process pair. I am having little trouble grasping it. Can anyone please explain how it is being achieved. Any help will be appreciated. Thanks.
#define N 1 00
typedef int semaphore;
semaphore mutex = 1 ;
semaphore empty = N;
semaphore full = 0;
void producer(void)
{
int item;
while (TRUE) {
item = produce_item( );
down( &empty);
down( &mutex);
inserUtem(item);
up(&mutex);
up(&full);
}
void consumer(void)
{
int item;
while (TRUE) {
down(&full);
down( &mutex);
item = remove_ item( );
up(&mutex);
up(&empty);
consume_item(item);
}
The (mutex) semahore is initialized to 1. Only one thread can get this one unit, all others are blocked. It’s only purpose is to prevent more than one thread, of any type, accessing the queue & so ensuring that a typical queue implementation is thread-safe.
One semaphore, (full), is initialized to zero and counts the number of items in the queue.
One semaphore (empty), is initialized to the queue length and counts the number of free spaces in the queue.
That’s it really. To shove an object on, first wait on (empty) to ensure that there is a free space, then wait on (mutex) to get access to the queue, push on the object, (yes, there will always be a space available – no need to check the queue count), signal (mutex) to unlock the queue, and finally signal (full) so that any consumer thread that is waiting, or will later turn up, can get a unit that represents an object in the queue.
To pop an object off, first wait on (full) to ensure that an object is available on the queue, then wait on (mutex) to get access to the queue, pop off the object, (yes, there will always be an object on the queue – no need to check the queue count), signal (mutex) to unlock the queue, and finally signal (empty) so that any producer thread that is waiting, or will later turn up, can get a unit that represents a free space in the queue.
This is Computer Science 101 stuff – an absolutely classic producer-consumer blocking queue.