TickQueue.cpp 2.4 KB

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