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.

device_context_manager.cc 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. #include "runtime/hardware/device_context_manager.h"
  17. namespace mindspore {
  18. namespace device {
  19. void DeviceContextManager::Register(const std::string &device_name, DeviceContextCreator &&device_context_creator) {
  20. if (device_context_creators_.find(device_name) == device_context_creators_.end()) {
  21. (void)device_context_creators_.emplace(device_name, device_context_creator);
  22. }
  23. }
  24. void DeviceContextManager::ClearDeviceContexts() {
  25. std::lock_guard<std::mutex> guard(lock_);
  26. for (auto &iter : device_contexts_) {
  27. MS_LOG(INFO) << "Release device " << iter.first;
  28. MS_EXCEPTION_IF_NULL(iter.second);
  29. iter.second->Destroy();
  30. }
  31. device_contexts_.clear();
  32. }
  33. DeviceContext *DeviceContextManager::GetOrCreateDeviceContext(const DeviceContextKey &device_context_key) {
  34. std::string device_context_key_str = device_context_key.ToString();
  35. std::lock_guard<std::mutex> guard(lock_);
  36. auto device_context_iter = device_contexts_.find(device_context_key_str);
  37. if (device_context_iter != device_contexts_.end()) {
  38. return device_context_iter->second.get();
  39. }
  40. std::shared_ptr<DeviceContext> device_context;
  41. auto creator_iter = device_context_creators_.find(device_context_key.device_name_);
  42. if (creator_iter != device_context_creators_.end()) {
  43. device_context = (creator_iter->second)(device_context_key);
  44. MS_EXCEPTION_IF_NULL(device_context);
  45. device_contexts_[device_context_key_str] = device_context;
  46. } else {
  47. MS_LOG(EXCEPTION) << "There is no device context creator for " << device_context_key.device_name_
  48. << " with device id " << device_context_key.device_id_;
  49. }
  50. return device_context.get();
  51. }
  52. } // namespace device
  53. } // namespace mindspore