Loading...
Searching...
No Matches
batch_queue.h
Go to the documentation of this file.
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. 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,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20#pragma once
21
22#include <glog/logging.h>
23
24#include <condition_variable>
25#include <list>
26
27namespace resdb {
28
29template <typename T>
31 struct BatchQueueItem {
32 std::vector<T> list;
33 };
34
35 public:
36 int num = 0;
37 BatchQueue() = default;
38 BatchQueue(const std::string& name, int batch_size)
39 : name_(name), batch_size_(batch_size) {}
40 void Push(T&& data) {
41 std::lock_guard<std::mutex> lk(mutex_);
42 if (queue_.empty() || queue_.back()->list.size() >= batch_size_) {
43 queue_.push_back(std::make_unique<BatchQueueItem>());
44 queue_.back()->list.reserve(batch_size_);
45 }
46 queue_.back()->list.push_back(std::move(data));
47 cv_.notify_all();
48 }
49
50 size_t Size() { return queue_.size(); }
51
52 std::vector<T> Pop(int timeout_ms) {
53 std::unique_ptr<BatchQueueItem> item = nullptr;
54 {
55 std::unique_lock<std::mutex> lk(mutex_);
56 if (timeout_ms > 0) {
57 cv_.wait_for(lk, std::chrono::microseconds(timeout_ms), [&] {
58 return !queue_.empty() && queue_.front()->list.size() >= batch_size_;
59 });
60 }
61 if (queue_.empty()) {
62 return std::vector<T>();
63 }
64 item = std::move(queue_.front());
65 queue_.pop_front();
66 }
67 return std::move(item->list);
68 }
69
70 private:
71 std::string name_;
72 std::condition_variable cv_;
73 std::mutex mutex_;
74 // std::queue<T> queue_ GUARDED_BY(mutex_);
75 std::list<std::unique_ptr<BatchQueueItem>> queue_;
76 size_t batch_size_;
77};
78
79} // namespace resdb
std::string data
std::vector< T > Pop(int timeout_ms)
Definition batch_queue.h:52
BatchQueue(const std::string &name, int batch_size)
Definition batch_queue.h:38
BatchQueue()=default
void Push(T &&data)
Definition batch_queue.h:40