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