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 2.3 kB

4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. try {
  23. if (monitor_thread_.joinable()) {
  24. monitor_thread_.join();
  25. }
  26. } catch (std::exception &e) {
  27. MS_LOG(ERROR) << "monitor thread join failed: " << e.what();
  28. }
  29. }
  30. void IterationTimer::Start(const std::chrono::milliseconds &duration) {
  31. std::unique_lock<std::mutex> lock(timer_mtx_);
  32. MS_LOG(INFO) << "The timer begin to start.";
  33. if (running_.load()) {
  34. MS_LOG(WARNING) << "The timer already started.";
  35. return;
  36. }
  37. running_ = true;
  38. end_time_ = CURRENT_TIME_MILLI + duration;
  39. monitor_thread_ = std::thread([&]() {
  40. while (running_.load()) {
  41. if (CURRENT_TIME_MILLI > end_time_) {
  42. timeout_callback_(false, "");
  43. running_ = false;
  44. }
  45. // The time tick is 1 millisecond.
  46. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  47. }
  48. });
  49. MS_LOG(INFO) << "The timer start success.";
  50. }
  51. void IterationTimer::Stop() {
  52. std::unique_lock<std::mutex> lock(timer_mtx_);
  53. MS_LOG(INFO) << "The timer begin to stop.";
  54. running_ = false;
  55. if (monitor_thread_.joinable()) {
  56. monitor_thread_.join();
  57. }
  58. MS_LOG(INFO) << "The timer stop success.";
  59. }
  60. void IterationTimer::SetTimeOutCallBack(const TimeOutCb &timeout_cb) {
  61. timeout_callback_ = timeout_cb;
  62. return;
  63. }
  64. bool IterationTimer::IsTimeOut(const std::chrono::milliseconds &timestamp) {
  65. return timestamp > end_time_ ? true : false;
  66. }
  67. bool IterationTimer::IsRunning() const { return running_; }
  68. } // namespace server
  69. } // namespace fl
  70. } // namespace mindspore