Yifan Hong | b93f050 | 2016-10-28 10:42:57 -0700 | [diff] [blame^] | 1 | /* |
| 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 Moreland | 7e3a2a2 | 2016-09-15 09:04:37 -0700 | [diff] [blame] | 17 | #include <condition_variable> |
| 18 | #include <mutex> |
| 19 | #include <queue> |
| 20 | #include <thread> |
| 21 | |
| 22 | /* Threadsafe queue. |
| 23 | */ |
| 24 | template <typename T> |
| 25 | struct 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 | |
| 41 | private: |
| 42 | std::condition_variable mCondition; |
| 43 | std::mutex mMutex; |
| 44 | std::queue<T> mQueue; |
| 45 | }; |
| 46 | |
| 47 | template <typename T> |
| 48 | T 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 | |
| 61 | template <typename T> |
| 62 | void 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 | |
| 71 | template <typename T> |
| 72 | size_t SynchronizedQueue<T>::size() { |
| 73 | std::unique_lock<std::mutex> lock(mMutex); |
| 74 | |
| 75 | return mQueue.size(); |
Yifan Hong | b93f050 | 2016-10-28 10:42:57 -0700 | [diff] [blame^] | 76 | } |