202. Thread pool with a single thread

In order to show how a thread pool with a single thread works, let's assume that we want to write a program that simulates an assembly line (or a conveyor) for checking and packing up bulbs using two workers.

By checking, we understand that the worker tests if the bulb lights up or not. By packing, we understand that the worker takes the verified bulb and put it in a box. This kind of process is very common in almost any factory.

The two workers are as follows:

  • A so-called producer (or checker) that is responsible for testing each bulb to see if the bulb lights up or not
  • A so-called consumer (or packer) that is responsible for packing each checked bulb into a box

This kind of problem is a perfect fit for the producer-consumer design pattern shown in the following diagram:

Most commonly, in this pattern, the producer and consumer communicate via a queue (the producer enqueues data, and the consumer dequeues data). This queue is known as the data buffer. Of course, depending on the process design, other data structures can play the role of data buffer as well.

Now, let's see how we can implement this pattern if the producer waits for the consumer to be available.

Later on, we will implement this pattern for a producer that doesn't wait for a consumer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.5.57