blob: 84ccace96e4a6f65240f0cd23539813d827820b5 [file] [log] [blame]
Prabir Pradhand5678112023-05-18 01:57:10 +00001/*
2 * Copyright 2023 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
17#pragma once
18
19#include <utils/threads.h>
20#include <list>
21#include <mutex>
22#include <optional>
23
24namespace android {
25
26/** A thread-safe FIFO queue. */
27template <class T>
28class SyncQueue {
29public:
Prabir Pradhan047695b2023-06-30 01:48:45 +000030 SyncQueue() = default;
31
32 SyncQueue(size_t capacity) : mCapacity(capacity) {}
33
Prabir Pradhand5678112023-05-18 01:57:10 +000034 /** Retrieve and remove the oldest object. Returns std::nullopt if the queue is empty. */
35 std::optional<T> pop() {
36 std::scoped_lock lock(mLock);
37 if (mQueue.empty()) {
38 return {};
39 }
40 T t = std::move(mQueue.front());
41 mQueue.erase(mQueue.begin());
42 return t;
43 };
44
Prabir Pradhan047695b2023-06-30 01:48:45 +000045 /**
46 * Add a new object to the queue.
47 * Return true if an element was successfully added.
48 * Return false if the queue is full.
49 */
Prabir Pradhand5678112023-05-18 01:57:10 +000050 template <class... Args>
Prabir Pradhan047695b2023-06-30 01:48:45 +000051 bool push(Args&&... args) {
Prabir Pradhand5678112023-05-18 01:57:10 +000052 std::scoped_lock lock(mLock);
Prabir Pradhan047695b2023-06-30 01:48:45 +000053 if (mCapacity && mQueue.size() == mCapacity) {
54 return false;
55 }
Prabir Pradhand5678112023-05-18 01:57:10 +000056 mQueue.emplace_back(args...);
Prabir Pradhan047695b2023-06-30 01:48:45 +000057 return true;
Prabir Pradhand5678112023-05-18 01:57:10 +000058 };
59
60private:
Prabir Pradhan047695b2023-06-30 01:48:45 +000061 const std::optional<size_t> mCapacity;
Prabir Pradhand5678112023-05-18 01:57:10 +000062 std::mutex mLock;
63 std::list<T> mQueue GUARDED_BY(mLock);
64};
65
66} // namespace android