1 /*
2  * Copyright (c) 2024 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 COMMUNICATIONNETSTACK_THREAD_SAFE_STORAGE_H
17 #define COMMUNICATIONNETSTACK_THREAD_SAFE_STORAGE_H
18 
19 #include <mutex>
20 #include <queue>
21 #include <utility>
22 #include <vector>
23 
24 #include "manual_reset_event.h"
25 #include "spinlock_mutex.h"
26 
27 namespace OHOS::NetStack::HttpOverCurl {
28 
29 template <typename T> class ThreadSafeStorage {
30 public:
31     void Push(const T &element);
32     std::vector<T> Flush();
33     [[nodiscard]] bool IsEmpty() const;
34     [[nodiscard]] const ManualResetEvent &GetSyncEvent() const;
35 
36 private:
37     spinlock_mutex queueMutex_;
38     std::queue<T> queue_;
39     ManualResetEvent syncEvent_;
40 };
41 
GetSyncEvent()42 template <typename T> const ManualResetEvent &ThreadSafeStorage<T>::GetSyncEvent() const
43 {
44     return syncEvent_;
45 }
46 
Push(const T & element)47 template <typename T> void ThreadSafeStorage<T>::Push(const T &element)
48 {
49     std::lock_guard lock(queueMutex_);
50     queue_.push(element);
51     syncEvent_.Set();
52 }
53 
Flush()54 template <typename T> std::vector<T> ThreadSafeStorage<T>::Flush()
55 {
56     std::vector<T> elementsToReturn;
57     std::lock_guard lock(queueMutex_);
58 
59     while (!queue_.empty()) {
60         elementsToReturn.push_back(std::move(queue_.front()));
61         queue_.pop();
62     }
63 
64     syncEvent_.Reset();
65     return elementsToReturn;
66 }
67 
IsEmpty()68 template <typename T> bool ThreadSafeStorage<T>::IsEmpty() const
69 {
70     std::lock_guard lock(queueMutex_);
71     return queue_.empty();
72 }
73 
74 } // namespace OHOS::NetStack::HttpOverCurl
75 
76 #endif // COMMUNICATIONNETSTACK_THREAD_SAFE_STORAGE_H
77