TickQueue.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include "TickQueue.h"
  2. #include "Block.h"
  3. TickQueue::TickQueue()
  4. : ReferenceCounter()
  5. {
  6. maxSize = 0;
  7. readPosition = 0;
  8. writePosition = 0;
  9. queue = 0;
  10. exit = 0;
  11. }
  12. TickQueue::~TickQueue()
  13. {
  14. delete[] queue;
  15. }
  16. void TickQueue::startNextTick(Framework::Array<Block*>* zSources)
  17. {
  18. std::unique_lock<std::mutex> lk(mutex);
  19. readPosition = 0;
  20. writePosition = 0;
  21. int count = zSources->getEintragAnzahl();
  22. if (count >= maxSize)
  23. {
  24. Block** temp = new Block * [count + 1000];
  25. memcpy(queue, temp, sizeof(Block*) * maxSize);
  26. memset(temp + sizeof(Block*) * maxSize, 0, sizeof(Block*) * (count + 1000 - maxSize));
  27. maxSize = count + 1000;
  28. delete[]queue;
  29. queue = temp;
  30. }
  31. for (Block* block : *zSources)
  32. queue[writePosition++] = block;
  33. lk.unlock();
  34. hasBlocks.notify_all();
  35. }
  36. void TickQueue::addToQueue(Block* zBlock)
  37. {
  38. std::unique_lock<std::mutex> lk(mutex);
  39. if (writePosition >= maxSize)
  40. {
  41. Block** temp = new Block * [maxSize + 1000];
  42. memcpy(queue, temp, sizeof(Block*) * maxSize);
  43. memset(temp + sizeof(Block*) * maxSize, 0, sizeof(Block*) * 1000);
  44. maxSize += 1000;
  45. delete[]queue;
  46. queue = temp;
  47. }
  48. queue[writePosition++] = zBlock;
  49. lk.unlock();
  50. hasBlocks.notify_one();
  51. }
  52. Block* TickQueue::zNextBlock(bool& waiting)
  53. {
  54. std::unique_lock<std::mutex> lk(mutex);
  55. if (readPosition == writePosition && exit)
  56. return 0;
  57. if (readPosition == writePosition)
  58. {
  59. lk.unlock();
  60. hasNoBlocks.notify_all();
  61. lk.lock();
  62. waiting = 1;
  63. hasBlocks.wait(lk, [this] { return readPosition < writePosition || exit; });
  64. waiting = 0;
  65. }
  66. if (readPosition < writePosition)
  67. return queue[readPosition++];
  68. return 0;
  69. }
  70. void TickQueue::requestExit()
  71. {
  72. std::unique_lock<std::mutex> lk(mutex);
  73. exit = 1;
  74. lk.unlock();
  75. hasBlocks.notify_all();
  76. hasNoBlocks.notify_all();
  77. }
  78. void TickQueue::waitForEmpty()
  79. {
  80. std::unique_lock<std::mutex> lk(mutex);
  81. if (readPosition != writePosition)
  82. hasNoBlocks.wait(lk, [this] { return readPosition == writePosition || exit; });
  83. }
  84. void TickQueue::postTick()
  85. {
  86. for(int i = 0; i < writePosition; i++)
  87. queue[i]->postTick();
  88. }