Implementing a multithreaded safe queue
In this section, we will see how to implement a simple multithreaded safe queue. The queue will be accessed by multiple threads, some of them adding elements to it (producer threads) and some of them removing elements from it (consumer threads). For starters, we are going to assume just two threads: one producer and one consumer.
Queues or first-in-first-outs (FIFOs) are a standard way of communication between threads. For example, if we need to receive packets containing data from a network connection as fast as possible, we may not have enough time in just one thread to receive all the packets and process them. In this case, we use a second thread to process the packets read by the first thread. Using just one consumer thread is simpler to synchronize (we will see how this is the case in Chapter 5), and we have a guarantee that the packets will be processed in the same order as they arrived and were copied to the queue by the producer thread...