TickQueue.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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,
  27. 0,
  28. sizeof(Block*) * (count + 1000 - maxSize));
  29. maxSize = count + 1000;
  30. delete[] queue;
  31. queue = temp;
  32. }
  33. for (Block* block : *zSources)
  34. queue[writePosition++] = block;
  35. lk.unlock();
  36. hasBlocks.notify_all();
  37. }
  38. void TickQueue::addToQueue(Block* zBlock)
  39. {
  40. std::unique_lock<std::mutex> lk(mutex);
  41. if (writePosition >= maxSize)
  42. {
  43. Block** temp = new Block*[maxSize + 1000];
  44. memcpy(queue, temp, sizeof(Block*) * maxSize);
  45. memset(temp + sizeof(Block*) * maxSize, 0, sizeof(Block*) * 1000);
  46. maxSize += 1000;
  47. delete[] queue;
  48. queue = temp;
  49. }
  50. queue[writePosition++] = zBlock;
  51. lk.unlock();
  52. hasBlocks.notify_one();
  53. }
  54. Block* TickQueue::zNextBlock(bool& waiting)
  55. {
  56. std::unique_lock<std::mutex> lk(mutex);
  57. if (readPosition == writePosition && exit) return 0;
  58. if (readPosition == writePosition)
  59. {
  60. lk.unlock();
  61. hasNoBlocks.notify_all();
  62. lk.lock();
  63. waiting = 1;
  64. hasBlocks.wait(
  65. lk, [this] { return readPosition < writePosition || exit; });
  66. waiting = 0;
  67. }
  68. if (readPosition < writePosition) return queue[readPosition++];
  69. return 0;
  70. }
  71. void TickQueue::requestExit()
  72. {
  73. std::unique_lock<std::mutex> lk(mutex);
  74. exit = 1;
  75. lk.unlock();
  76. hasBlocks.notify_all();
  77. hasNoBlocks.notify_all();
  78. }
  79. void TickQueue::waitForEmpty()
  80. {
  81. std::unique_lock<std::mutex> lk(mutex);
  82. if (readPosition != writePosition)
  83. hasNoBlocks.wait(
  84. lk, [this] { return readPosition == writePosition || exit; });
  85. }
  86. void TickQueue::postTick()
  87. {
  88. for (int i = 0; i < writePosition; i++)
  89. queue[i]->postTick();
  90. }