Line data Source code
1 : /**
2 : * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3 : * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4 : * CANN Open Software License Agreement Version 2.0 (the "License").
5 : * Please refer to the License for details. You may not use this file except in compliance with the License.
6 : * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7 : * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 : * See LICENSE in the root of the software repository for the full text of the License.
9 : */
10 :
11 : #include "endpoint_map.h"
12 : #include <unordered_map>
13 : #include <memory>
14 : #include <mutex>
15 :
16 : namespace hcomm {
17 :
18 : static std::unordered_map<EndpointHandle, std::unique_ptr<Endpoint>> g_EndpointMap;
19 : static std::mutex g_EndpointMapMutex;
20 :
21 58 : void HcommEndpointMap::AddEndpoint(EndpointHandle handle, std::unique_ptr<Endpoint> endpoint)
22 : {
23 58 : std::lock_guard<std::mutex> lock(g_EndpointMapMutex);
24 :
25 58 : auto it = g_EndpointMap.find(handle);
26 58 : if (it != g_EndpointMap.end()) {
27 0 : it->second = std::move(endpoint);
28 0 : return;
29 : }
30 :
31 58 : g_EndpointMap.emplace(handle, std::move(endpoint));
32 58 : return;
33 58 : }
34 :
35 31 : bool HcommEndpointMap::RemoveEndpoint(EndpointHandle handle)
36 : {
37 31 : std::lock_guard<std::mutex> lock(g_EndpointMapMutex);
38 :
39 31 : auto it = g_EndpointMap.find(handle);
40 31 : if (it != g_EndpointMap.end()) {
41 29 : g_EndpointMap.erase(it);
42 29 : return true;
43 : }
44 2 : return false;
45 31 : }
46 :
47 0 : bool HcommEndpointMap::UpdateEndpoint(
48 : EndpointHandle handle,
49 : std::unique_ptr<Endpoint> newEndpoint)
50 : {
51 0 : std::lock_guard<std::mutex> lock(g_EndpointMapMutex);
52 :
53 0 : auto it = g_EndpointMap.find(handle);
54 0 : if (it != g_EndpointMap.end()) {
55 0 : it->second = std::move(newEndpoint);
56 0 : return true;
57 : }
58 0 : return false;
59 0 : }
60 :
61 162 : Endpoint* HcommEndpointMap::GetEndpoint(EndpointHandle handle)
62 : {
63 162 : std::lock_guard<std::mutex> lock(g_EndpointMapMutex);
64 :
65 162 : auto it = g_EndpointMap.find(handle);
66 162 : if (it != g_EndpointMap.end()) {
67 139 : return it->second.get(); // 返回裸指针,不转移所有权
68 : }
69 23 : return nullptr;
70 162 : }
71 : } // namespace hcomm
|