• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 cvd {
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 
Push(T && t)53   void Push(T&& t) {
54     std::lock_guard<std::mutex> guard(m_);
55     DropItemsIfAtCapacity();
56     items_.push_back(std::move(t));
57     new_item_.notify_one();
58   }
59 
Push(const T & t)60   void Push(const T& t) {
61     std::lock_guard<std::mutex> guard(m_);
62     DropItemsIfAtCapacity();
63     items_.push_back(t);
64     new_item_.notify_one();
65   }
66 
67  private:
DropItemsIfAtCapacity()68   void DropItemsIfAtCapacity() {
69     if (max_elements_ && max_elements_ == items_.size()) {
70       max_elements_handler_(&items_);
71     }
72   }
73 
74   std::mutex m_;
75   std::size_t max_elements_{};
76   std::function<void(QueueImpl*)> max_elements_handler_{};
77   std::condition_variable new_item_;
78   QueueImpl items_;
79 };
80 }  // namespace cvd
81