GATE / CS ARCHIVE

GATE CSE 2002 / QUESTION 20(b)

Mutex additions for multiple producers and consumers

Operating Systems · Synchronization & Concurrency · Full GATE CSE 2002 paper

GATE 2002, Q20(b) Descriptive
Report issue

Synchronization & Concurrency

Question 20(b), GATE 2002: Circular buffer size 100, indices first=last=0, semaphores b_full=0,b_empty=100. Producer repeats produce item; p1 blank; put into buf[first]; first=(first+1)%100; p2 blank. Consumer repeats c1 blank; take from buf[last]; last=(last+1)%100; c2 blank; consume item. Original20(b): Introduce one additional semaphore and one statement at each location: immediately after p1, before p2, after c1, before c2 so the program supports multiple producers/consumers.
Question 20(b), GATE 2002: Circular buffer size 100, indices first=last=0, semaphores b_full=0,b_empty=100. Producer repeats produce item; p1 blank; put into buf[first]; first=(first+1)%100; p2 blank. Consumer repeats c1 blank; take from buf[last]; last=(last+1)%100; c2 blank; consume item. Original20(b): Introduce one additional semaphore and one statement at each location: immediately after p1, before p2, after c1, before c2 so the program supports multiple producers/consumers.
Question 20(b), GATE 2002: Circular buffer size 100, indices first=last=0, semaphores b_full=0,b_empty=100. Producer repeats produce item; p1 blank; put into buf[first]; first=(first+1)%100; p2 blank. Consumer repeats c1 blank; take from buf[last]; last=(last+1)%100; c2 blank; consume item. Original20(b): Introduce one additional semaphore and one statement at each location: immediately after p1, before p2, after c1, before c2 so the program supports multiple producers/consumers.
Tap to enlarge
Answer & solution

Answer: Initialize semaphore mutex=1; after p1 and c1 insert wait(mutex); before p2 and c2 insert signal(mutex). (no official key was published)

Add a binary semaphore mutex initialized to one. Insert wait(mutex) immediately after p1 and immediately after c1, and signal(mutex) immediately before p2 and immediately before c2. The resulting operation order is:
Producer: wait(b_empty); wait(mutex); write buf[first]; advance first; signal(mutex); signal(b_full).
Consumer: wait(b_full); wait(mutex); read buf[last]; advance last; signal(mutex); signal(b_empty).
This serializes updates to the shared buffer and indices across all producers and consumers. Slot availability is awaited before taking the mutex. Reversing that order can deadlock, for example a consumer holding the mutex while waiting for an item prevents a producer from inserting one. Producing and consuming the actual item stay outside the mutex-protected buffer operations.

Original paper, page 10