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 93 : void HcommEndpointMap::AddEndpoint(EndpointHandle handle, std::unique_ptr<Endpoint> endpoint)
22 : {
23 93 : std::lock_guard<std::mutex> lock(g_EndpointMapMutex);
24 :
25 93 : auto it = g_EndpointMap.find(handle);
26 93 : if (it != g_EndpointMap.end()) {
27 0 : it->second = std::move(endpoint);
28 0 : return;
29 : }
30 :
31 93 : g_EndpointMap.emplace(handle, std::move(endpoint));
32 93 : return;
33 93 : }
34 :
35 64 : bool HcommEndpointMap::RemoveEndpoint(EndpointHandle handle)
36 : {
37 64 : std::lock_guard<std::mutex> lock(g_EndpointMapMutex);
38 :
39 64 : auto it = g_EndpointMap.find(handle);
40 64 : if (it != g_EndpointMap.end()) {
41 62 : g_EndpointMap.erase(it);
42 62 : return true;
43 : }
44 2 : return false;
45 64 : }
46 :
47 0 : bool HcommEndpointMap::UpdateEndpoint(EndpointHandle handle, std::unique_ptr<Endpoint> newEndpoint)
48 : {
49 0 : std::lock_guard<std::mutex> lock(g_EndpointMapMutex);
50 :
51 0 : auto it = g_EndpointMap.find(handle);
52 0 : if (it != g_EndpointMap.end()) {
53 0 : it->second = std::move(newEndpoint);
54 0 : return true;
55 : }
56 0 : return false;
57 0 : }
58 :
59 359 : Endpoint* HcommEndpointMap::GetEndpoint(EndpointHandle handle)
60 : {
61 359 : std::lock_guard<std::mutex> lock(g_EndpointMapMutex);
62 :
63 359 : auto it = g_EndpointMap.find(handle);
64 359 : if (it != g_EndpointMap.end()) {
65 332 : return it->second.get(); // 返回裸指针,不转移所有权
66 : }
67 27 : return nullptr;
68 359 : }
69 : } // namespace hcomm
|