• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2025 The Android Open Source Project
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 #pragma once
17 
18 #include <mutex>
19 #include <queue>
20 
21 namespace android {
22 namespace os {
23 namespace statsd {
24 
25 template <typename T>
26 class ThreadSafeQueue {
27 public:
pop()28     std::optional<T> pop() {
29         std::unique_lock<std::mutex> lock(mMutex);
30         if (mQueue.empty()) {
31             return std::nullopt;
32         }
33         T value = std::move(mQueue.front());
34         mQueue.pop();
35         return value;
36     }
37 
push(const T value)38     void push(const T value) {
39         std::unique_lock<std::mutex> lock(mMutex);
40         mQueue.push(value);
41     }
42 
empty()43     bool empty() const {
44         std::unique_lock<std::mutex> lock(mMutex);
45         return mQueue.empty();
46     }
47 
48 private:
49     mutable std::mutex mMutex;
50     std::queue<T> mQueue;
51 };
52 
53 }  // namespace statsd
54 }  // namespace os
55 }  // namespace android
56