task_scheduler.cpp 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. #include "task_scheduler.h"
  2. #include <util/system/thread.h>
  3. #include <util/string/cast.h>
  4. #include <util/stream/output.h>
  5. TTaskScheduler::ITask::~ITask() {}
  6. TTaskScheduler::IRepeatedTask::~IRepeatedTask() {}
  7. class TTaskScheduler::TWorkerThread
  8. : public ISimpleThread
  9. {
  10. public:
  11. TWorkerThread(TTaskScheduler& state)
  12. : Scheduler_(state)
  13. {
  14. }
  15. TString DebugState = "?";
  16. TString DebugId = "";
  17. private:
  18. void* ThreadProc() noexcept override {
  19. Scheduler_.WorkerFunc(this);
  20. return nullptr;
  21. }
  22. private:
  23. TTaskScheduler& Scheduler_;
  24. };
  25. TTaskScheduler::TTaskScheduler(size_t threadCount, size_t maxTaskCount)
  26. : MaxTaskCount_(maxTaskCount)
  27. {
  28. for (size_t i = 0; i < threadCount; ++i) {
  29. Workers_.push_back(new TWorkerThread(*this));
  30. Workers_.back()->DebugId = ToString(i);
  31. }
  32. }
  33. TTaskScheduler::~TTaskScheduler() {
  34. try {
  35. Stop();
  36. } catch (...) {
  37. Cdbg << "task scheduled destruction error: " << CurrentExceptionMessage();
  38. }
  39. }
  40. void TTaskScheduler::Start() {
  41. for (auto& w : Workers_) {
  42. w->Start();
  43. }
  44. }
  45. void TTaskScheduler::Stop() {
  46. with_lock (Lock_) {
  47. IsStopped_ = true;
  48. CondVar_.BroadCast();
  49. }
  50. for (auto& w: Workers_) {
  51. w->Join();
  52. }
  53. Workers_.clear();
  54. Queue_.clear();
  55. }
  56. size_t TTaskScheduler::GetTaskCount() const {
  57. return static_cast<size_t>(AtomicGet(TaskCounter_));
  58. }
  59. namespace {
  60. class TTaskWrapper
  61. : public TTaskScheduler::ITask
  62. , TNonCopyable
  63. {
  64. public:
  65. TTaskWrapper(TTaskScheduler::ITaskRef task, TAtomic& counter)
  66. : Task_(task)
  67. , Counter_(counter)
  68. {
  69. AtomicIncrement(Counter_);
  70. }
  71. ~TTaskWrapper() override {
  72. AtomicDecrement(Counter_);
  73. }
  74. private:
  75. TInstant Process() override {
  76. return Task_->Process();
  77. }
  78. private:
  79. TTaskScheduler::ITaskRef Task_;
  80. TAtomic& Counter_;
  81. };
  82. }
  83. bool TTaskScheduler::Add(ITaskRef task, TInstant expire) {
  84. with_lock (Lock_) {
  85. if (!IsStopped_ && Workers_.size() > 0 && GetTaskCount() + 1 <= MaxTaskCount_) {
  86. ITaskRef newTask = new TTaskWrapper(task, TaskCounter_);
  87. Queue_.insert(std::make_pair(expire, TTaskHolder(newTask)));
  88. if (!Queue_.begin()->second.WaitingWorker) {
  89. CondVar_.Signal();
  90. }
  91. return true;
  92. }
  93. }
  94. return false;
  95. }
  96. namespace {
  97. class TRepeatedTask
  98. : public TTaskScheduler::ITask
  99. {
  100. public:
  101. TRepeatedTask(TTaskScheduler::IRepeatedTaskRef task, TDuration period, TInstant deadline)
  102. : Task_(task)
  103. , Period_(period)
  104. , Deadline_(deadline)
  105. {
  106. }
  107. private:
  108. TInstant Process() final {
  109. Deadline_ += Period_;
  110. if (Task_->Process()) {
  111. return Deadline_;
  112. } else {
  113. return TInstant::Max();
  114. }
  115. }
  116. private:
  117. TTaskScheduler::IRepeatedTaskRef Task_;
  118. TDuration Period_;
  119. TInstant Deadline_;
  120. };
  121. }
  122. bool TTaskScheduler::Add(IRepeatedTaskRef task, TDuration period) {
  123. const TInstant deadline = Now() + period;
  124. ITaskRef t = new TRepeatedTask(task, period, deadline);
  125. return Add(t, deadline);
  126. }
  127. const bool debugOutput = false;
  128. void TTaskScheduler::ChangeDebugState(TWorkerThread* thread, const TString& state) {
  129. if (!debugOutput) {
  130. Y_UNUSED(thread);
  131. Y_UNUSED(state);
  132. return;
  133. }
  134. thread->DebugState = state;
  135. TStringStream ss;
  136. ss << Now() << " " << thread->DebugId << ":\t";
  137. for (auto& w : Workers_) {
  138. ss << w->DebugState << " ";
  139. }
  140. ss << " [" << Queue_.size() << "] [" << TaskCounter_ << "]" << Endl;
  141. Cerr << ss.Str();
  142. }
  143. bool TTaskScheduler::Wait(TWorkerThread* thread, TQueueIterator& toWait) {
  144. ChangeDebugState(thread, "w");
  145. toWait->second.WaitingWorker = thread;
  146. return !CondVar_.WaitD(Lock_, toWait->first);
  147. }
  148. void TTaskScheduler::ChooseFromQueue(TQueueIterator& toWait) {
  149. for (TQueueIterator it = Queue_.begin(); it != Queue_.end(); ++it) {
  150. if (!it->second.WaitingWorker) {
  151. if (toWait == Queue_.end()) {
  152. toWait = it;
  153. } else if (it->first < toWait->first) {
  154. toWait->second.WaitingWorker = nullptr;
  155. toWait = it;
  156. }
  157. break;
  158. }
  159. }
  160. }
  161. void TTaskScheduler::WorkerFunc(TWorkerThread* thread) {
  162. TThread::SetCurrentThreadName("TaskSchedWorker");
  163. TQueueIterator toWait = Queue_.end();
  164. ITaskRef toDo;
  165. for (;;) {
  166. TInstant repeat = TInstant::Max();
  167. if (!!toDo) {
  168. try {
  169. repeat = toDo->Process();
  170. } catch (...) {
  171. Cdbg << "task scheduler error: " << CurrentExceptionMessage();
  172. }
  173. }
  174. with_lock (Lock_) {
  175. ChangeDebugState(thread, "f");
  176. if (IsStopped_) {
  177. ChangeDebugState(thread, "s");
  178. return ;
  179. }
  180. if (!!toDo) {
  181. if (repeat < TInstant::Max()) {
  182. Queue_.insert(std::make_pair(repeat, TTaskHolder(toDo)));
  183. }
  184. }
  185. toDo = nullptr;
  186. ChooseFromQueue(toWait);
  187. if (toWait != Queue_.end()) {
  188. if (toWait->first <= Now() || Wait(thread, toWait)) {
  189. toDo = toWait->second.Task;
  190. Queue_.erase(toWait);
  191. toWait = Queue_.end();
  192. if (!Queue_.empty() && !Queue_.begin()->second.WaitingWorker && Workers_.size() > 1) {
  193. CondVar_.Signal();
  194. }
  195. ChangeDebugState(thread, "p");
  196. }
  197. } else {
  198. ChangeDebugState(thread, "e");
  199. CondVar_.WaitI(Lock_);
  200. }
  201. }
  202. }
  203. }