1 | /** |
2 | * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved. |
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 | * \author Haichao.chc |
17 | * \date Oct 2020 |
18 | * \brief Concurrent bitmap which is thread-safe for add/del operations |
19 | */ |
20 | |
21 | #pragma once |
22 | |
23 | #include <ailego/container/bitmap.h> |
24 | #include <ailego/parallel/lock.h> |
25 | |
26 | namespace proxima { |
27 | namespace be { |
28 | namespace index { |
29 | |
30 | /* |
31 | * Concurrent bitmap, support test/set in multi-threads |
32 | */ |
33 | class ConcurrentBitmap { |
34 | public: |
35 | //! Construtor |
36 | ConcurrentBitmap() = default; |
37 | |
38 | //! Destructor |
39 | ~ConcurrentBitmap() = default; |
40 | |
41 | public: |
42 | //! Test if num pos bit exist |
43 | bool test(size_t num) const { |
44 | bool found = false; |
45 | // Remove shared lock here!! |
46 | // It will slow down search performance significantly |
47 | found = bitmap_.test(num); |
48 | return found; |
49 | } |
50 | |
51 | //! Set num pos bit |
52 | void set(size_t num) { |
53 | rw_lock_.lock(); |
54 | bitmap_.set(num); |
55 | rw_lock_.unlock(); |
56 | } |
57 | |
58 | //! Reset num pos bit |
59 | void reset(size_t num) { |
60 | rw_lock_.lock(); |
61 | bitmap_.reset(num); |
62 | rw_lock_.unlock(); |
63 | } |
64 | |
65 | //! Cleanup all bits |
66 | void clear() { |
67 | rw_lock_.lock(); |
68 | bitmap_.clear(); |
69 | rw_lock_.unlock(); |
70 | } |
71 | |
72 | private: |
73 | mutable ailego::SharedMutex rw_lock_{}; |
74 | ailego::Bitmap bitmap_{}; |
75 | }; |
76 | |
77 | |
78 | } // end namespace index |
79 | } // namespace be |
80 | } // end namespace proxima |
81 | |