You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

iteration_timer.cc 1.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Copyright 2021 Huawei Technologies Co., Ltd
  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 "fl/server/iteration_timer.h"
  17. namespace mindspore {
  18. namespace fl {
  19. namespace server {
  20. IterationTimer::~IterationTimer() {
  21. running_ = false;
  22. if (monitor_thread_.joinable()) {
  23. monitor_thread_.join();
  24. }
  25. }
  26. void IterationTimer::Start(const std::chrono::milliseconds &duration) {
  27. if (running_.load()) {
  28. MS_LOG(WARNING) << "The timer already started.";
  29. return;
  30. }
  31. running_ = true;
  32. end_time_ = CURRENT_TIME_MILLI + duration;
  33. monitor_thread_ = std::thread([&]() {
  34. while (running_.load()) {
  35. if (CURRENT_TIME_MILLI > end_time_) {
  36. timeout_callback_(false, "");
  37. running_ = false;
  38. }
  39. // The time tick is 1 millisecond.
  40. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  41. }
  42. });
  43. }
  44. void IterationTimer::Stop() {
  45. running_ = false;
  46. if (monitor_thread_.joinable()) {
  47. monitor_thread_.join();
  48. }
  49. }
  50. void IterationTimer::SetTimeOutCallBack(const TimeOutCb &timeout_cb) {
  51. timeout_callback_ = timeout_cb;
  52. return;
  53. }
  54. bool IterationTimer::IsTimeOut(const std::chrono::milliseconds &timestamp) {
  55. return timestamp > end_time_ ? true : false;
  56. }
  57. bool IterationTimer::IsRunning() const { return running_; }
  58. } // namespace server
  59. } // namespace fl
  60. } // namespace mindspore