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 "proc_reged_mem_mgr_cache.h"
12 : #include "log.h"
13 :
14 : namespace hcomm {
15 :
16 203 : std::shared_ptr<ProcRegedMemMgrCache> ProcRegedMemMgrCache::GetHolder()
17 : {
18 : // 构造 private,make_shared 无法调用,只能 new。static 保证只 new 一次。
19 203 : static std::shared_ptr<ProcRegedMemMgrCache> holder(new ProcRegedMemMgrCache());
20 203 : return holder;
21 : }
22 :
23 : std::shared_ptr<RegedMemMgr>
24 200 : ProcRegedMemMgrCache::GetOrCreate(const MemMgrCacheKey& key, std::function<std::shared_ptr<RegedMemMgr>()> creator)
25 : {
26 200 : std::lock_guard<std::mutex> lock(mtx_);
27 200 : auto it = cacheMap_.find(key);
28 200 : if (it != cacheMap_.end()) {
29 135 : it->second.refCount++;
30 135 : HCCL_INFO(
31 : "[ProcRegedMemMgrCache][GetOrCreate] cache hit, refCount[%llu]",
32 : static_cast<unsigned long long>(it->second.refCount));
33 135 : return it->second.mgrPtr;
34 : }
35 :
36 65 : auto mgrPtr = creator();
37 65 : MemMgrEntry entry{mgrPtr, 1};
38 65 : cacheMap_.emplace(key, entry);
39 65 : HCCL_INFO("[ProcRegedMemMgrCache][GetOrCreate] cache miss, new instance inserted");
40 65 : return mgrPtr;
41 200 : }
42 :
43 203 : void ProcRegedMemMgrCache::Release(const MemMgrCacheKey& key)
44 : {
45 203 : std::lock_guard<std::mutex> lock(mtx_);
46 203 : auto it = cacheMap_.find(key);
47 203 : if (it == cacheMap_.end()) {
48 3 : HCCL_WARNING("[ProcRegedMemMgrCache][Release] key not found, skip release");
49 3 : return;
50 : }
51 200 : if (it->second.refCount > 0) {
52 200 : it->second.refCount--;
53 : }
54 200 : if (it->second.refCount == 0) {
55 65 : cacheMap_.erase(it);
56 65 : HCCL_INFO("[ProcRegedMemMgrCache][Release] refCount zero, entry erased");
57 : } else {
58 135 : HCCL_INFO(
59 : "[ProcRegedMemMgrCache][Release] refCount remain [%llu]",
60 : static_cast<unsigned long long>(it->second.refCount));
61 : }
62 203 : }
63 :
64 : } // namespace hcomm
|