Advertisement
Guest User

Threaded queue

a guest
May 27th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. class TQCantAlloc : ResourceException
  2. {
  3. };
  4.  
  5. template<typename T>
  6. class ThreadedQueue
  7. {
  8. public:
  9.          ThreadedQueue( bool fThrowOnFailue = true );
  10.     void Push( T &t );
  11.     T    Pop();
  12.  
  13. private:
  14.     CondVar      m_cv;
  15.     std::list<T> m_lstT;
  16.     bool         m_fThrowOnFailue;
  17.     int          m_failures;
  18. };
  19.  
  20. template<typename T>
  21. ThreadedQueue<T>::ThreadedQueue( bool fThrowOnFailue )
  22. {
  23.     m_fThrowOnFailue = fThrowOnFailue;
  24.     m_failures       = 0;
  25. }
  26.  
  27. template<typename T>
  28. void ThreadedQueue<T>::Push( T &t )
  29. {
  30.     CondVar::Guard cvg( &m_cv );
  31.  
  32.     try
  33.     {
  34.         m_lstT.push_back( t );
  35.     }
  36.     catch( std::exception & )
  37.     {
  38.         if( m_fThrowOnFailue )
  39.             m_failures++;
  40.  
  41.         cvg.Release();
  42.         throw TQCantAlloc();   
  43.     }
  44.  
  45.     cvg.Release();
  46. }
  47.  
  48. template<typename T>
  49. T ThreadedQueue<T>::Pop()
  50. {
  51.     CondVar::Guard cvg( &m_cv );
  52.     T              t;
  53.  
  54.     while( m_lstT.empty() && m_failures == 0 )
  55.         cvg.Wait();
  56.  
  57.     if( m_failures )
  58.         m_failures--,
  59.         throw TQCantAlloc();
  60.  
  61.     t = m_lstT.front();
  62.     m_lstT.pop_front();
  63.  
  64.     return t;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement