• 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 PYBIND_API_GIL_SCOPED_LONG_RUNNING_H_
18 #define PYBIND_API_GIL_SCOPED_LONG_RUNNING_H_
19 
20 #include <memory>
21 
22 #include "pybind11/pybind11.h"
23 
24 #include "include/common/utils/scoped_long_running.h"
25 #include "include/common/profiler.h"
26 
27 namespace py = pybind11;
28 
29 namespace mindspore {
30 class GilScopedLongRunningHook : public ScopedLongRunningHook {
31  public:
Enter()32   void Enter() override {
33     if (PyGILState_Check() != 0) {
34       release_ = std::make_unique<py::gil_scoped_release>();
35     }
36   }
Leave()37   void Leave() noexcept override { release_ = nullptr; }
38 
39  private:
40   std::unique_ptr<py::gil_scoped_release> release_;
41 };
42 
43 class GilReleaseWithCheck {
44  public:
GilReleaseWithCheck()45   GilReleaseWithCheck() {
46     if (Py_IsInitialized() != 0 && PyGILState_Check() != 0) {
47       release_ = std::make_unique<py::gil_scoped_release>();
48     }
49   }
50 
~GilReleaseWithCheck()51   ~GilReleaseWithCheck() {
52     runtime::ProfilerRecorder profiler(runtime::ProfilerModule::kPynative, runtime::ProfilerEvent::kPyNativeGilAcquire,
53                                        runtime::ProfilerRecorder::kNoName, false);
54     release_ = nullptr;
55   }
56 
57  private:
58   std::unique_ptr<py::gil_scoped_release> release_;
59 };
60 }  // namespace mindspore
61 #endif  // PYBIND_API_GIL_SCOPED_LONG_RUNNING_H_
62