43da05c24a1927f9c13449aa9476e21b0055c237
[platform/core/appfw/pkgmgr-info.git] / src / server / cache_flag.hh
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd 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
17 #ifndef CACHE_FLAG_HH_
18 #define CACHE_FLAG_HH_
19
20 #include <mutex>
21 #include <shared_mutex>
22
23 namespace pkgmgr_server {
24
25 #ifndef EXPORT_API
26 #define EXPORT_API __attribute__((visibility("default")))
27 #endif
28
29 class EXPORT_API CacheFlag {
30  public:
31   enum class EXPORT_API Status {
32     UNPREPARED,
33     PREPARING,
34     PREPARED
35   };
36
37   static bool SetPreparing() {
38     bool ret = false;
39     std::unique_lock<std::shared_mutex> u(status_lock_);
40     if (status_ == Status::UNPREPARED) {
41       status_ = Status::PREPARING;
42       ret = true;
43     }
44     return ret;
45   }
46
47   static void SetStatus(Status status) {
48     std::unique_lock<std::shared_mutex> u(status_lock_);
49     status_ = status;
50   }
51
52   static Status GetStatus() {
53     std::shared_lock<std::shared_mutex> s(status_lock_);
54     return status_;
55   }
56
57   static std::unique_lock<std::shared_mutex> GetWriterLock() {
58     return std::unique_lock<std::shared_mutex>(lock_);
59   }
60
61   static void WriterUnLock() {
62     lock_.unlock();
63   }
64
65   static std::shared_lock<std::shared_mutex> GetReaderLock() {
66     return std::shared_lock<std::shared_mutex>(lock_, std::defer_lock);
67   }
68
69   static void ReaderUnLock() {
70     lock_.unlock_shared();
71   }
72
73  private:
74   static inline Status status_;
75   static inline std::shared_mutex status_lock_;
76   static inline std::shared_mutex lock_;
77 };
78
79 }  // namespace pkgmgr_server
80
81 #endif  // CACHE_FLAG_HH_