1 #pragma once 2 3 /* 4 * Copyright (C) 2016 The Android Open Source Project 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 #include <mutex> 20 #include <condition_variable> 21 #include <deque> 22 #include <utility> 23 #include <iterator> 24 25 namespace cuttlefish { 26 // Simple queue with Push and Pop capabilities. 27 // If the max_elements argument is passed to the constructor, and Push is called 28 // when the queue holds max_elements items, the max_elements_handler is called 29 // with a pointer to the internal QueueImpl. The call is made while holding 30 // the guarding mutex; operations on the QueueImpl will not interleave with 31 // other threads calling Push() or Pop(). 32 // The QueueImpl type will be a SequenceContainer. 33 template <typename T> 34 class ThreadSafeQueue { 35 public: 36 using QueueImpl = std::deque<T>; 37 ThreadSafeQueue() = default; ThreadSafeQueue(std::size_t max_elements,std::function<void (QueueImpl *)> max_elements_handler)38 explicit ThreadSafeQueue(std::size_t max_elements, 39 std::function<void(QueueImpl*)> max_elements_handler) 40 : max_elements_{max_elements}, 41 max_elements_handler_{std::move(max_elements_handler)} {} 42 Pop()43 T Pop() { 44 std::unique_lock<std::mutex> guard(m_); 45 while (items_.empty()) { 46 new_item_.wait(guard); 47 } 48 auto t = std::move(items_.front()); 49 items_.pop_front(); 50 return t; 51 } 52 PopAll()53 QueueImpl PopAll() { 54 std::unique_lock<std::mutex> guard(m_); 55 while (items_.empty()) { 56 new_item_.wait(guard); 57 } 58 return std::move(items_); 59 } 60 Push(T && t)61 void Push(T&& t) { 62 std::lock_guard<std::mutex> guard(m_); 63 DropItemsIfAtCapacity(); 64 items_.push_back(std::move(t)); 65 new_item_.notify_one(); 66 } 67 Push(const T & t)68 void Push(const T& t) { 69 std::lock_guard<std::mutex> guard(m_); 70 DropItemsIfAtCapacity(); 71 items_.push_back(t); 72 new_item_.notify_one(); 73 } 74 75 private: DropItemsIfAtCapacity()76 void DropItemsIfAtCapacity() { 77 if (max_elements_ && max_elements_ == items_.size()) { 78 max_elements_handler_(&items_); 79 } 80 } 81 82 std::mutex m_; 83 std::size_t max_elements_{}; 84 std::function<void(QueueImpl*)> max_elements_handler_{}; 85 std::condition_variable new_item_; 86 QueueImpl items_; 87 }; 88 } // namespace cuttlefish 89