TickQueue.cpp 1.9 KB

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