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