2.4.13. queue.hpp#

2.4.13.1. Source code#

 1// University of Florida EEL6528
 2// Tan F. Wong
 3// Jan 17, 2021
 4
 5#pragma once
 6
 7#include <mutex>
 8
 9// Define template for thread-safe FIFO 
10template<class T>
11class MutexFIFO {
12  public:
13    void push(T);
14    bool pop(T&);
15    int size();
16    void lock();
17    void unlock();
18    std::list<T> queue; // May make this private if want max protection
19  private:
20    std::recursive_mutex mtx;
21};
22
23template <class T>
24void MutexFIFO<T>::push(T entry) {
25    std::lock_guard<std::recursive_mutex> scoped_lock(mtx);
26    queue.push_back(entry);
27}
28
29template <class T>
30int MutexFIFO<T>::size(void) {
31    std::lock_guard<std::recursive_mutex> scoped_lock(mtx);
32    return queue.size();
33}
34
35template <class T>
36bool MutexFIFO<T>::pop(T& entry) {
37    std::lock_guard<std::recursive_mutex> scoped_lock(mtx);
38    bool is_not_empty = not queue.empty();
39    if (is_not_empty) {
40        entry = queue.front();
41        queue.pop_front();
42    }
43    return is_not_empty;
44}
45
46template <class T>
47void MutexFIFO<T>::lock(void) {
48    mtx.lock();
49}
50
51template <class T>
52void MutexFIFO<T>::unlock(void) {
53    mtx.unlock();
54}