95fa94c606fc4c5e07bd973b89fce9eee1a1997d
[folly.git] / folly / executors / task_queue / UnboundedBlockingQueue.h
1 /*
2  * Copyright 2017 Facebook, Inc.
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 #pragma once
18
19 #include <folly/Synchronized.h>
20 #include <folly/concurrency/UnboundedQueue.h>
21 #include <folly/executors/task_queue/BlockingQueue.h>
22 #include <folly/synchronization/LifoSem.h>
23
24 namespace folly {
25
26 template <class T>
27 class UnboundedBlockingQueue : public BlockingQueue<T> {
28  public:
29   virtual ~UnboundedBlockingQueue() {}
30
31   void add(T item) override {
32     queue_.enqueue(std::move(item));
33     sem_.post();
34   }
35
36   T take() override {
37     T item;
38     while (!queue_.try_dequeue(item)) {
39       sem_.wait();
40     }
41     return item;
42   }
43
44   size_t size() override {
45     return queue_.size();
46   }
47
48  private:
49   LifoSem sem_;
50   UMPMCQueue<T, false> queue_;
51 };
52
53 } // namespace folly