Although producer-consumer synchronization is easy to implement with
semaphores, it’s also possible to implement it with mutexes. The basic idea is
to have the producer and the consumer share a mutex. A flag variable that’s
initialized to false by the main thread indicates whether there’s anything to
consume. With two threads we’d execute something like this:
So if the consumer gets into the loop first, it will see there’s no message
available and return to the call to pthread mutex lock. It will continue
this process until the producer creates the message. Write a Pthreads program that implements this version of producer-consumer synchronization
with two threads. Can you generalize this so that it works with 2k threads–
odd-ranked threads are consumers and even-ranked threads are producers?
Can you generalize this so that each thread is both a producer and a consumer? For example, suppose that thread q “sends” a message to thread
(q + 1) mod t and “receives” a message from thread (q − 1 + t) mod t? Does
this use busy-waiting?