blob: 62efd5598a414e1ab09f1a901907851809bb67d2 [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:
30 /** Retrieve and remove the oldest object. Returns std::nullopt if the queue is empty. */
31 std::optional<T> pop() {
32 std::scoped_lock lock(mLock);
33 if (mQueue.empty()) {
34 return {};
35 }
36 T t = std::move(mQueue.front());
37 mQueue.erase(mQueue.begin());
38 return t;
39 };
40
41 /** Add a new object to the queue. */
42 template <class... Args>
43 void push(Args&&... args) {
44 std::scoped_lock lock(mLock);
45 mQueue.emplace_back(args...);
46 };
47
48private:
49 std::mutex mLock;
50 std::list<T> mQueue GUARDED_BY(mLock);
51};
52
53} // namespace android