Executor.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /*
  2. * Copyright 2009-2017 Alibaba Cloud All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "Executor.h"
  17. #include <alibabacloud/core/Runnable.h>
  18. using namespace AlibabaCloud;
  19. Executor *Executor::self_ = nullptr;
  20. Executor::Executor() :
  21. cvMutex_(),
  22. shutdown_(true),
  23. tasksQueue_(),
  24. tasksQueueMutex_(),
  25. thread_()
  26. {
  27. self_ = this;
  28. }
  29. Executor::~Executor()
  30. {
  31. self_ = nullptr;
  32. shutdown();
  33. }
  34. Executor * Executor::instance()
  35. {
  36. return self_;
  37. }
  38. bool Executor::start()
  39. {
  40. if (!isShutdown())
  41. return true;
  42. auto threadMain = [this]()
  43. {
  44. while (!shutdown_)
  45. {
  46. while (!tasksQueue_.empty())
  47. {
  48. Runnable *task = nullptr;
  49. {
  50. std::lock_guard<std::mutex> lock(tasksQueueMutex_);
  51. if (!tasksQueue_.empty())
  52. {
  53. task = tasksQueue_.front();
  54. tasksQueue_.pop();
  55. }
  56. }
  57. if (task) {
  58. task->run();
  59. delete task;
  60. }
  61. }
  62. if (!shutdown_) {
  63. std::unique_lock<std::mutex> lk(cvMutex_);
  64. cv_.wait(lk);
  65. }
  66. }
  67. };
  68. shutdown_ = false;
  69. thread_ = std::thread(threadMain);
  70. return true;
  71. }
  72. bool Executor::isShutdown()const
  73. {
  74. return shutdown_;
  75. }
  76. void Executor::execute(Runnable* task)
  77. {
  78. if (isShutdown())
  79. return;
  80. std::lock_guard<std::mutex> locker(tasksQueueMutex_);
  81. tasksQueue_.push(task);
  82. wakeUp();
  83. }
  84. void Executor::wakeUp()
  85. {
  86. std::unique_lock<std::mutex> lk(cvMutex_);
  87. cv_.notify_one();
  88. }
  89. void Executor::shutdown()
  90. {
  91. if (isShutdown())
  92. return;
  93. {
  94. std::lock_guard<std::mutex> locker(tasksQueueMutex_);
  95. while (tasksQueue_.size() > 0) {
  96. auto task = tasksQueue_.front();
  97. delete task;
  98. tasksQueue_.pop();
  99. }
  100. }
  101. shutdown_ = true;
  102. wakeUp();
  103. if (thread_.joinable())
  104. thread_.join();
  105. }