Executor.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /*
  2. * Copyright 1999-2019 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. namespace AlibabaCloud {
  19. Executor *Executor::self_ = nullptr;
  20. Executor::Executor() :
  21. cvMutex_(),
  22. shutdown_(true),
  23. tasksQueue_(),
  24. tasksQueueMutex_(),
  25. thread_() {
  26. self_ = this;
  27. }
  28. Executor::~Executor() {
  29. self_ = nullptr;
  30. shutdown();
  31. }
  32. Executor * Executor::instance() {
  33. return self_;
  34. }
  35. bool Executor::start() {
  36. if (!isShutdown())
  37. return true;
  38. auto threadMain = [this]() {
  39. while (!shutdown_) {
  40. while (!tasksQueue_.empty()) {
  41. Runnable *task = nullptr;
  42. {
  43. std::lock_guard<std::mutex> lock(tasksQueueMutex_);
  44. if (!tasksQueue_.empty()) {
  45. task = tasksQueue_.front();
  46. tasksQueue_.pop();
  47. }
  48. }
  49. if (task) {
  50. task->run();
  51. delete task;
  52. }
  53. }
  54. if (!shutdown_) {
  55. std::unique_lock<std::mutex> lk(cvMutex_);
  56. cv_.wait(lk);
  57. }
  58. }
  59. };
  60. shutdown_ = false;
  61. thread_ = std::thread(threadMain);
  62. return true;
  63. }
  64. bool Executor::isShutdown()const {
  65. return shutdown_;
  66. }
  67. void Executor::execute(Runnable* task) {
  68. if (isShutdown())
  69. return;
  70. std::lock_guard<std::mutex> locker(tasksQueueMutex_);
  71. tasksQueue_.push(task);
  72. wakeUp();
  73. }
  74. void Executor::wakeUp() {
  75. std::unique_lock<std::mutex> lk(cvMutex_);
  76. cv_.notify_one();
  77. }
  78. void Executor::shutdown() {
  79. if (isShutdown())
  80. return;
  81. {
  82. std::lock_guard<std::mutex> locker(tasksQueueMutex_);
  83. while (tasksQueue_.size() > 0) {
  84. auto task = tasksQueue_.front();
  85. delete task;
  86. tasksQueue_.pop();
  87. }
  88. }
  89. shutdown_ = true;
  90. wakeUp();
  91. if (thread_.joinable())
  92. thread_.join();
  93. }
  94. } // namespace AlibabaCloud