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.

scoped_long_running.h 1.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Copyright 2020 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. #ifndef MINDSPORE_CCSRC_UTILS_SCOPED_LONG_RUNNING_H_
  17. #define MINDSPORE_CCSRC_UTILS_SCOPED_LONG_RUNNING_H_
  18. #include <memory>
  19. #include <utility>
  20. namespace mindspore {
  21. // Base Class for scoped long running code.
  22. // Enter() should release some global resoure, like Python GIL;
  23. // Leave() should acquire the same global resource released.
  24. class ScopedLongRunningHook {
  25. public:
  26. ScopedLongRunningHook() = default;
  27. virtual ~ScopedLongRunningHook() = default;
  28. virtual void Enter() = 0;
  29. virtual void Leave() = 0;
  30. };
  31. using ScopedLongRunningHookPtr = std::unique_ptr<ScopedLongRunningHook>;
  32. // Before calling into long-running code, construct this RAII class to release global resource
  33. // like Python GIL.
  34. class ScopedLongRunning {
  35. public:
  36. ScopedLongRunning() {
  37. if (hook_ != nullptr) {
  38. hook_->Enter();
  39. }
  40. }
  41. ~ScopedLongRunning() {
  42. if (hook_ != nullptr) {
  43. hook_->Leave();
  44. }
  45. }
  46. static void SetHook(ScopedLongRunningHookPtr hook) {
  47. if (hook_ == nullptr) {
  48. hook_ = std::move(hook);
  49. }
  50. }
  51. private:
  52. static ScopedLongRunningHookPtr hook_;
  53. };
  54. } // namespace mindspore
  55. #endif // MINDSPORE_CCSRC_UTILS_SCOPED_LONG_RUNNING_H_