Extending The Solution for Multiple Producers And Consumers

Let's build on the solution from the previous lesson to handle the case of more than one producer and consumer.

Let us now imagine that MAX is greater than 1 (say MAX=10). For this example, let us assume that there are multiple producers and multiple consumers. We now have a problem: a race condition. Do you see where it occurs? (take some time and look for it in the code in the previous lesson) If you can’t see it, here’s a hint: look more closely at the put() and get() code.

OK, let’s understand the issue. Imagine two producers (PaP_a and PbP_b) both calling into put() at roughly the same time. Assume producer PaP_a gets to run first, and just starts to fill the first buffer entry (fill=0 at Line F1). Before PaP_a gets a chance to increment the fill counter to 1, it is interrupted. Producer PbP_b starts to run, and at Line F1 it also puts its data into the 0th element of the buffer, which means that the old data there is overwritten! This action is a no-no; we don’t want any data from the producer to be lost.

A solution: adding mutual exclusion

As you can see, what we’ve forgotten here is mutual exclusion. The filling of a buffer and incrementing of the index into the buffer is a critical section, and thus must be guarded carefully. So let’s use our friend the binary semaphore and add some locks. Look at the code snippet given below.

Get hands-on with 1400+ tech skills courses.