The thread-safe queue
The next data structure we are going to consider is the queue. It is again a very simple data structure, conceptually an array that is accessible from both ends: the data is added to the end of the array and removed from the beginning of it. There are some very important differences between the queue and the stack when it comes to implementation. There are also many similarities, and we will refer to the previous section frequently.
Just like the stack, the STL has a queue container, std::queue
, and it has the exact same problem when it comes to concurrency: the interface for removing elements is not transactional, it requires three separate member function calls. If we wanted to use std::queue
with a lock to create a thread-safe queue, we would have to wrap it just like we did with the stack:
03_queue.C
template <typename T> class mt_queue { std::queue<T> s_; mutable spinlock l_; public: void...