• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef ATOMIC_MAP_H
17 #define ATOMIC_MAP_H
18 
19 #include <atomic>
20 #include <map>
21 #include "nocopyable.h"
22 
23 namespace OHOS {
24 namespace Rosen {
25 template<class Key, class Value>
26 class AtomicMap {
27 public:
insert(const std::pair<Key,Value> & kv)28     void insert(const std::pair<Key, Value>& kv)
29     {
30         locked();
31         data_.insert(kv);
32         unlocked();
33     }
34 
erase(const Key & key)35     void erase(const Key& key)
36     {
37         locked();
38         data_.erase(key);
39         unlocked();
40     }
41 
find(Key k)42     auto find(Key k)
43     {
44         locked();
45         auto key = data_.find(k);
46         unlocked();
47         return key;
48     }
49 
count(Key k)50     int count(Key k)
51     {
52         locked();
53         int size = data_.count(k);
54         unlocked();
55         return size;
56     }
57 
isExistAndRemove(Key k,uint32_t value)58     bool isExistAndRemove(Key k, uint32_t value)
59     {
60         locked();
61         if (data_.count(k) <= 0) {
62             unlocked();
63             return false;
64         }
65         if (data_[k] == value) {
66             data_.erase(k);
67             unlocked();
68             return true;
69         }
70         unlocked();
71         return false;
72     }
73 
isExist(Key k,uint32_t value)74     bool isExist(Key k, uint32_t value)
75     {
76         locked();
77         if (data_.count(k) <= 0) {
78             unlocked();
79             return false;
80         }
81         if (data_[k] == value) {
82             unlocked();
83             return true;
84         }
85         unlocked();
86         return false;
87     }
88 private:
locked()89     void locked()
90     {
91         bool expect = false;
92         while (!isWritingOrReading_.compare_exchange_weak(expect, true, std::memory_order_relaxed)) {
93             expect = false;
94         }
95     }
96 
unlocked()97     void unlocked()
98     {
99         isWritingOrReading_.store(false);
100     }
101 
102     std::map<Key, Value> data_;
103     std::atomic<bool> isWritingOrReading_ { false };
104 };
105 } // Rosen
106 } // OHOS
107 #endif // ATOMIC_MAP_H