blob: 72414114b798ae08d4d1ceb4458bd4ad84c48a1d [file] [log] [blame]
Yifan Hongb93f0502016-10-28 10:42:57 -07001/*
2 * Copyright (C) 2016 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
Steven Moreland7e3a2a22016-09-15 09:04:37 -070017#include <condition_variable>
18#include <mutex>
19#include <queue>
20#include <thread>
21
22/* Threadsafe queue.
23 */
24template <typename T>
25struct SynchronizedQueue {
26
27 /* Gets an item from the front of the queue.
28 *
29 * Blocks until the item is available.
30 */
31 T wait_pop();
32
33 /* Puts an item onto the end of the queue.
34 */
35 void push(const T& item);
36
37 /* Gets the size of the array.
38 */
39 size_t size();
40
41private:
42 std::condition_variable mCondition;
43 std::mutex mMutex;
44 std::queue<T> mQueue;
45};
46
47template <typename T>
48T SynchronizedQueue<T>::wait_pop() {
49 std::unique_lock<std::mutex> lock(mMutex);
50
51 mCondition.wait(lock, [this]{
52 return !this->mQueue.empty();
53 });
54
55 T item = mQueue.front();
56 mQueue.pop();
57
58 return item;
59}
60
61template <typename T>
62void SynchronizedQueue<T>::push(const T &item) {
63 {
64 std::unique_lock<std::mutex> lock(mMutex);
65 mQueue.push(item);
66 }
67
68 mCondition.notify_one();
69}
70
71template <typename T>
72size_t SynchronizedQueue<T>::size() {
73 std::unique_lock<std::mutex> lock(mMutex);
74
75 return mQueue.size();
Yifan Hongb93f0502016-10-28 10:42:57 -070076}