• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 #ifndef MINDSPORE_CCSRC_RUNTIME_HARDWARE_DEVICE_CONTEXT_MANAGER_H_
18 #define MINDSPORE_CCSRC_RUNTIME_HARDWARE_DEVICE_CONTEXT_MANAGER_H_
19 
20 #include <map>
21 #include <string>
22 #include <memory>
23 #include <utility>
24 #include <functional>
25 #include <mutex>
26 #include <vector>
27 #include "runtime/hardware/device_context.h"
28 namespace mindspore {
29 namespace device {
30 using DeviceContextCreator = std::function<std::shared_ptr<DeviceContext>(const DeviceContextKey &)>;
31 
32 class DeviceContextManager {
33  public:
GetInstance()34   static DeviceContextManager &GetInstance() {
35     static DeviceContextManager instance;
36     return instance;
37   }
38   void Register(const std::string &device_name, DeviceContextCreator &&device_context_creator);
39   DeviceContext *GetOrCreateDeviceContext(const DeviceContextKey &device_context_key);
40   void UpdateDeviceContextKey(const DeviceContextKey &old_key, const DeviceContextKey &new_key);
41   void ClearDeviceContexts();
42 
43  private:
44   DeviceContextManager() = default;
45   ~DeviceContextManager() = default;
46   DISABLE_COPY_AND_ASSIGN(DeviceContextManager);
47 
48   // The string converted from DeviceContextKey -> DeviceContextPtr.
49   std::map<std::string, DeviceContextPtr> device_contexts_;
50   // The name of device -> DeviceContextCreator.
51   std::map<std::string, DeviceContextCreator> device_context_creators_;
52 };
53 
54 class DeviceContextRegister {
55  public:
DeviceContextRegister(const std::string & device_name,DeviceContextCreator && runtime_creator)56   DeviceContextRegister(const std::string &device_name, DeviceContextCreator &&runtime_creator) {
57     DeviceContextManager::GetInstance().Register(device_name, std::move(runtime_creator));
58   }
59   ~DeviceContextRegister() = default;
60 };
61 
62 #define MS_REGISTER_DEVICE(DEVICE_NAME, DEVICE_CONTEXT_CLASS)            \
63   static const DeviceContextRegister g_device_##DEVICE_NAME##_reg(       \
64     DEVICE_NAME, [](const DeviceContextKey &device_context_key) {        \
65       return std::make_shared<DEVICE_CONTEXT_CLASS>(device_context_key); \
66     });
67 }  // namespace device
68 }  // namespace mindspore
69 #endif  // MINDSPORE_CCSRC_RUNTIME_HARDWARE_DEVICE_CONTEXT_MANAGER_H_
70