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 17 #ifndef CHRE_UTIL_FIXED_SIZE_BLOCKING_QUEUE_H_ 18 #define CHRE_UTIL_FIXED_SIZE_BLOCKING_QUEUE_H_ 19 20 #include <deque> 21 22 #include "chre/platform/condition_variable.h" 23 #include "chre/platform/mutex.h" 24 #include "chre/util/array_queue.h" 25 #include "chre/util/non_copyable.h" 26 27 namespace chre { 28 29 /** 30 * Implements a thread-safe blocking queue that blocks when popping an element 31 * if necessary. 32 */ 33 template <typename ElementType, size_t kSize> 34 class FixedSizeBlockingQueue : public NonCopyable { 35 public: 36 /** 37 * Pushes an element into the queue and notifies any waiting threads that an 38 * element is available. 39 * 40 * @param The element to be pushed. 41 * 42 * @return true if the element is pushed successfully. 43 */ 44 bool push(const ElementType& element); 45 46 /** 47 * Pops one element from the queue. If the queue is empty, the thread will 48 * block until an element has been pushed. 49 * 50 * @return The element that was popped. 51 */ 52 ElementType pop(); 53 54 /** 55 * Determines whether or not the BlockingQueue is empty. 56 */ 57 bool empty(); 58 59 private: 60 //! The mutex used to ensure thread-safety. 61 Mutex mMutex; 62 63 //! The condition variable used to implement the blocking behavior of the 64 //! queue. 65 ConditionVariable mConditionVariable; 66 67 //! The underlying fixed size container backing the queue. 68 ArrayQueue<ElementType, kSize> mQueue; 69 }; 70 71 } // namespace chre 72 73 #include "chre/util/fixed_size_blocking_queue_impl.h" 74 75 #endif // CHRE_UTIL_FIXED_SIZE_BLOCKING_QUEUE_H_ 76