Executor.cc 2.3 KB

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