LCOV - code coverage report
Current view: top level - Utils - ThreadSafeQueue.h (source / functions) Coverage Total Hit
Test: OdbDesign Test Coverage Lines: 34.4 % 61 21
Test Date: 2026-11-21 03:51:50 Functions: 27.3 % 11 3
Legend: Lines: hit not hit

            Line data    Source code
       1              : //
       2              : // Created by nam20485 on 5/25/22.
       3              : //
       4              : 
       5              : #pragma once
       6              : 
       7              : #include <queue>
       8              : #include <mutex>
       9              : #include <condition_variable>
      10              : #include <atomic>
      11              : #include <iostream>
      12              : #include <sstream>
      13              : #include <functional>
      14              : #include <chrono>
      15              : 
      16              : 
      17              : namespace Utils
      18              : {
      19              :     /** std::_queue wrapped in thread-safety mechanisms
      20              :      *
      21              :      * @tparam T: type of _queue's items
      22              :      */
      23              :     template <typename T>
      24              :     class ThreadSafeQueue
      25              :     {
      26              :     public:
      27              :         typedef std::function<void(const std::string&)> internalLogHandlerProc;
      28              : 
      29              :         enum class wait_result
      30              :         {
      31              :             timed_out,
      32              :             interrupted,
      33              :             notified
      34              :         };
      35              : 
      36          125 :         ThreadSafeQueue()
      37          125 :             : _interrupted(false)
      38              :         {
      39          125 :         }
      40              : 
      41              :         /** Push an object onto the _queue in a thread-safe manner
      42              :          *
      43              :          * @param item: item to push onto _queue
      44              :          */
      45              :         void push(T&& item);
      46              : 
      47              :         /** Get a reference to the head of the _queue in a type-safe manner
      48              :          *
      49              :          * @param wait: whether to wait for the _queue to become not empty and notified
      50              :          * @return reference to the item
      51              :          */
      52              :         T& front(bool wait);
      53              : 
      54              :         /** Remove last item off the _queue
      55              :          *
      56              :          */
      57              :         void pop();
      58              : 
      59              :         /** Set the interrupt and notify any wait()'s on the _queue without push();ing an item
      60              :          *
      61              :          */
      62              :         void interrupt();
      63              : 
      64              :         /**
      65              :          * Wait indefinitely for the _queue to be notified by either push() or interrupt()
      66              :          * @return wait_result specifying result of waiting, one of: { notified, interrupted }
      67              :          */
      68              :         wait_result wait();
      69              : 
      70              :         /**
      71              :          * Waits given duration for the _queue to be notified by either push() or interrupt(), or to time out
      72              :          * @param wait_ms std::chrono::duration specifying duration, in ms, to wait before timing out
      73              :          * @return wait_result specifying result of waiting, one of: { notified, interrupted, timed_out }
      74              :          * */
      75              :         wait_result wait(std::chrono::milliseconds wait_ms);
      76              : 
      77              :         /** Check if _queue is empty
      78              :          *
      79              :          * @return true if _queue is empty, false otherwise
      80              :          */
      81              :         bool empty();
      82              : 
      83              :         /**
      84              :          * Sets a function that is used to handle internal-level log messages. Invoked when logInternal() is called.
      85              :          * @param internal_log_handler: function to invoke when internal messages need to be logged
      86              :          */
      87              :         void registerInternalLogHandler(internalLogHandlerProc internalLogHandler);
      88              : 
      89              :     private:
      90              :         std::mutex _m;
      91              :         std::condition_variable _cv;
      92              :         std::queue<T> _queue;
      93              :         std::atomic_bool _interrupted;
      94              : 
      95              :         internalLogHandlerProc _internalLogHandler;
      96              : 
      97              :         void logInternal(const std::string& message);
      98              :     };
      99              : 
     100              : 
     101              :     template<typename T>
     102       429440 :     void ThreadSafeQueue<T>::push(T&& item)
     103              :     {
     104              :         {
     105       429440 :             logInternal("[ThreadSafeQueue<TResults>::push] enter, taking lock...");
     106              : 
     107              :             // unlock once scope is exited
     108       429440 :             std::lock_guard lock(_m);
     109              : 
     110       429440 :             std::stringstream ss;
     111       429440 :             ss << "[ThreadSafeQueue<TResults>::push] lock taken, pushing item (_queue.size(): " << _queue.size() << ')';
     112       429440 :             logInternal(ss.str());
     113              : 
     114       429440 :             _queue.push(item);
     115              : 
     116       429440 :             ss.str(""); // clear the stream out
     117       429440 :             ss << "[ThreadSafeQueue<TResults>::push] item pushed, _queue.size(): " << _queue.size();
     118       429440 :             logInternal(ss.str());
     119       429440 :         }
     120              : 
     121       429440 :         logInternal("[ThreadSafeQueue<TResults>::push] lock given up, notifying...");
     122              : 
     123              :         // unlock before notifying
     124       429440 :         _cv.notify_one();
     125              : 
     126       429440 :         logInternal("[ThreadSafeQueue<TResults>::push] _cv notified, exit");
     127       429440 :     }
     128              : 
     129              :     template<typename T>
     130            0 :     T& ThreadSafeQueue<T>::front(bool wait)
     131              :     {
     132            0 :         std::unique_lock lock(_m);
     133            0 :         if (wait)
     134              :         {
     135            0 :             _cv.wait(lock,
     136            0 :                 [&]
     137              :                 {
     138            0 :                     return _queue.empty() == false;
     139              :                 });
     140              :         }
     141            0 :         return _queue.front();
     142            0 :     }
     143              : 
     144              :     template<typename T>
     145            0 :     void ThreadSafeQueue<T>::pop()
     146              :     {
     147            0 :         std::lock_guard lock(_m);
     148            0 :         _queue.pop();
     149            0 :     }
     150              : 
     151              :     template<typename T>
     152            0 :     void ThreadSafeQueue<T>::interrupt()
     153              :     {
     154              :         // lock and notify
     155              :         {
     156            0 :             std::unique_lock lock(_m);
     157              : 
     158              :             // set interrupt to return from wait even if _queue is empty
     159            0 :             _interrupted.store(true);
     160            0 :         }
     161            0 :         _cv.notify_one();
     162            0 :     }
     163              : 
     164              :     template<typename T>
     165            0 :     typename ThreadSafeQueue<T>::wait_result ThreadSafeQueue<T>::wait()
     166              :     {
     167            0 :         logInternal("[ThreadSafeQueue<TResults>::wait] enter, taking lock...");
     168              : 
     169              :         // wait until _queue is not empty _OR_ interrupt has been set
     170            0 :         std::unique_lock lock(_m);
     171              : 
     172            0 :         logInternal("[ThreadSafeQueue<TResults>::wait] lock taken, begin waiting...");
     173              : 
     174            0 :         _cv.wait(lock,
     175            0 :             [&]
     176              :             {
     177            0 :                 return _queue.empty() == false || _interrupted.load();
     178              :             });
     179              : 
     180            0 :         std::stringstream ss;
     181            0 :         ss << "[ThreadSafeQueue<TResults>::wait] wait returned, exiting (_queue.size() => " << _queue.size() << ", _interrupted = " << _interrupted.load() << ')';
     182            0 :         logInternal(ss.str());
     183              : 
     184              :         // return whether _interrupted was tripped
     185            0 :         if (_interrupted.load())
     186              :         {
     187            0 :             return ThreadSafeQueue<T>::wait_result::interrupted;
     188              :         }
     189              :         else
     190              :         {
     191            0 :             return ThreadSafeQueue<T>::wait_result::notified;
     192              :         }
     193            0 :     }
     194              : 
     195              :     template<typename T>
     196              :     typename ThreadSafeQueue<T>::wait_result ThreadSafeQueue<T>::wait(std::chrono::milliseconds wait_ms)
     197              :     {
     198              :         logInternal("[ThreadSafeQueue<TResults>::wait] enter, taking lock...");
     199              : 
     200              :         // wait until _queue is not empty _OR_ interrupt has been set
     201              :         std::unique_lock lock(_m);
     202              : 
     203              :         logInternal("[ThreadSafeQueue<TResults>::wait] lock taken, begin waiting...");
     204              : 
     205              :         auto expired = !_cv.wait_for(lock, wait_ms, // NOLINT(clion-misra-cpp2008-5-3-1)
     206              :             [&]
     207              :             {
     208              :                 return _queue.empty() == false || _interrupted.load();
     209              :             });
     210              : 
     211              :         std::stringstream ss;
     212              :         ss << "[ThreadSafeQueue<TResults>::wait] wait returned, exiting (_queue.size() => " << _queue.size() << ", _interrupted = " << _interrupted.load() << ')';
     213              :         logInternal(ss.str());
     214              : 
     215              :         wait_result wait_result;
     216              :         if (expired)
     217              :         {
     218              :             wait_result = ThreadSafeQueue<T>::wait_result::timed_out;
     219              :         }
     220              :         else if (_interrupted.load())
     221              :         {
     222              :             wait_result = ThreadSafeQueue<T>::wait_result::interrupted;
     223              :         }
     224              :         else
     225              :         {
     226              :             wait_result = ThreadSafeQueue<T>::wait_result::notified;
     227              :         }
     228              :         return wait_result;
     229              :     }
     230              : 
     231              :     template<typename T>
     232            0 :     bool ThreadSafeQueue<T>::empty()
     233              :     {
     234            0 :         std::unique_lock lock(_m);
     235            0 :         return _queue.empty();
     236            0 :     }
     237              : 
     238              :     template<typename T>
     239      2147200 :     void ThreadSafeQueue<T>::logInternal(const std::string& message)
     240              :     {
     241      2147200 :         if (_internalLogHandler)
     242              :         {
     243            0 :             _internalLogHandler(message);
     244              :         }
     245      2147200 :     }
     246              : 
     247              :     template<typename T>
     248            0 :     void ThreadSafeQueue<T>::registerInternalLogHandler(ThreadSafeQueue::internalLogHandlerProc internalLogHandler)
     249              :     {
     250            0 :         _internalLogHandler = std::move(internalLogHandler);
     251            0 :     }
     252              : 
     253              : } // namespace Lib::Utils
        

Generated by: LCOV version 2.0-1