1 /** 2 * Copyright 2019 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_BACKEND_SESSION_SESSION_FACTORY_H_ 17 #define MINDSPORE_CCSRC_BACKEND_SESSION_SESSION_FACTORY_H_ 18 19 #include <functional> 20 #include <map> 21 #include <memory> 22 #include <string> 23 #include <utility> 24 #include <mutex> 25 #include "utils/ms_utils.h" 26 #include "backend/common/session/session_basic.h" 27 #include "include/backend/visible.h" 28 29 namespace mindspore { 30 namespace session { 31 using SessionCreator = std::function<std::shared_ptr<SessionBasic>()>; 32 class BACKEND_EXPORT SessionFactory { 33 public: 34 SessionFactory() = default; 35 ~SessionFactory() = default; 36 37 static SessionFactory &Get(); 38 void Register(const std::string &device_name, SessionCreator &&session_creator); 39 void Clear(); 40 std::shared_ptr<SessionBasic> Create(const std::string &device_name); 41 42 private: 43 DISABLE_COPY_AND_ASSIGN(SessionFactory) 44 std::map<std::string, SessionCreator> session_creators_; 45 inline static std::shared_ptr<SessionFactory> instance_; 46 inline static std::once_flag instance_flag_; 47 }; 48 49 class SessionRegistrar { 50 public: SessionRegistrar(const std::string & device_name,SessionCreator && session_creator)51 SessionRegistrar(const std::string &device_name, SessionCreator &&session_creator) { 52 SessionFactory::Get().Register(device_name, std::move(session_creator)); 53 } 54 ~SessionRegistrar() = default; 55 }; 56 57 #define MS_REG_SESSION(DEVICE_NAME, SESSION_CLASS) \ 58 static const SessionRegistrar g_session_registrar__##DEVICE_NAME##_##_reg( \ 59 DEVICE_NAME, []() { return std::make_shared<SESSION_CLASS>(); }); 60 } // namespace session 61 } // namespace mindspore 62 63 #endif // MINDSPORE_CCSRC_BACKEND_SESSION_SESSION_FACTORY_H_ 64