Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

130 lines
2.6 KiB

  1. //+---------------------------------------------------------------------------
  2. //
  3. // Microsoft Windows
  4. // Copyright (C) Microsoft Corporation, 1996 - 1999.
  5. //
  6. // File: circq.hxx
  7. //
  8. // Contents: First-in-first-out circular queue template
  9. //
  10. // History: 96/Apr/12 dlee Created
  11. //
  12. //----------------------------------------------------------------------------
  13. #pragma once
  14. template<class T> class TFifoCircularQueue
  15. {
  16. public:
  17. TFifoCircularQueue( unsigned maxRequests ) :
  18. _cRequests( 0 ),
  19. _iFirst( 0 ),
  20. _maxRequests( maxRequests ),
  21. _fEnableAdditions( TRUE )
  22. {
  23. _aEntries = new T [ _maxRequests ];
  24. RtlZeroMemory( _aEntries, sizeof T * _maxRequests );
  25. }
  26. ~TFifoCircularQueue()
  27. {
  28. delete [] _aEntries;
  29. }
  30. BOOL Any() const { return 0 != _cRequests; }
  31. unsigned Count() { return _cRequests; }
  32. unsigned MaxRequests() { return _maxRequests; }
  33. void DisableAdditions()
  34. {
  35. CLock lock( _mutex );
  36. _fEnableAdditions = FALSE;
  37. }
  38. void EnableAdditions()
  39. {
  40. CLock lock( _mutex );
  41. _fEnableAdditions = TRUE;
  42. }
  43. BOOL IsFull( )
  44. {
  45. // NOTE - locking not needed for read access.
  46. Win4Assert( _cRequests <= _maxRequests );
  47. return ( _maxRequests == _cRequests );
  48. }
  49. BOOL Add( T & Entry )
  50. {
  51. CLock lock( _mutex );
  52. if ( _maxRequests == _cRequests || !_fEnableAdditions )
  53. return FALSE;
  54. Win4Assert( _cRequests < _maxRequests );
  55. unsigned iNew = ( _iFirst + _cRequests ) % _maxRequests;
  56. Win4Assert( iNew < _maxRequests );
  57. Entry.Acquire( _aEntries[ iNew ] );
  58. _cRequests++;
  59. return TRUE;
  60. }
  61. BOOL RemoveTop( T & Entry )
  62. {
  63. CLock lock( _mutex );
  64. if ( 0 == _cRequests )
  65. return FALSE;
  66. Entry = _aEntries[ _iFirst ];
  67. RtlZeroMemory( &_aEntries[ _iFirst ], sizeof T );
  68. _iFirst++;
  69. _cRequests--;
  70. if ( _maxRequests == _iFirst )
  71. _iFirst = 0;
  72. Win4Assert( _iFirst < _maxRequests );
  73. return TRUE;
  74. }
  75. BOOL AcquireTop( T & item )
  76. {
  77. CLock lock( _mutex );
  78. if ( 0 == _cRequests )
  79. return FALSE;
  80. _aEntries[ _iFirst ].Acquire( item );
  81. _iFirst++;
  82. _cRequests--;
  83. if ( _maxRequests == _iFirst )
  84. _iFirst = 0;
  85. Win4Assert( _iFirst < _maxRequests );
  86. return TRUE;
  87. }
  88. private:
  89. unsigned _cRequests;
  90. unsigned _iFirst;
  91. unsigned _maxRequests;
  92. BOOL _fEnableAdditions;
  93. T * _aEntries;
  94. CMutexSem _mutex;
  95. };