MYNT-EYE-S-SDK/src/internal/async_callback_impl.h

93 lines
2.4 KiB
C
Raw Normal View History

2018-05-31 10:39:42 +03:00
// Copyright 2018 Slightech Co., Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef MYNTEYE_INTERNAL_ASYNC_CALLBACK_IMPL_H_ // NOLINT
#define MYNTEYE_INTERNAL_ASYNC_CALLBACK_IMPL_H_
#pragma once
#include <string>
#include <utility>
2018-09-04 10:12:04 +03:00
#include "mynteye/logger.h"
2018-05-31 10:39:42 +03:00
MYNTEYE_BEGIN_NAMESPACE
template <class Data>
2018-05-31 15:36:17 +03:00
AsyncCallback<Data>::AsyncCallback(
2018-07-11 10:04:14 +03:00
std::string name, callback_t callback, std::size_t max_data_size)
2018-05-31 15:36:17 +03:00
: name_(std::move(name)),
callback_(std::move(callback)),
count_(0),
2018-07-11 10:04:14 +03:00
max_data_size_(max_data_size) {
2018-05-31 10:39:42 +03:00
VLOG(2) << __func__;
running_ = true;
thread_ = std::thread(&AsyncCallback<Data>::Run, this);
}
template <class Data>
AsyncCallback<Data>::~AsyncCallback() {
VLOG(2) << __func__;
{
std::lock_guard<std::mutex> _(mtx_);
running_ = false;
++count_;
}
cv_.notify_one();
if (thread_.joinable()) {
thread_.join();
}
}
template <class Data>
void AsyncCallback<Data>::PushData(Data data) {
std::lock_guard<std::mutex> _(mtx_);
2018-07-11 10:04:14 +03:00
if (max_data_size_ <= 0) {
2018-05-31 15:36:17 +03:00
datas_.clear();
2018-07-11 10:04:14 +03:00
} else if (max_data_size_ == datas_.size()) { // >= 1
datas_.erase(datas_.begin());
2018-05-31 15:36:17 +03:00
}
datas_.push_back(data);
2018-05-31 10:39:42 +03:00
++count_;
cv_.notify_one();
}
template <class Data>
void AsyncCallback<Data>::Run() {
VLOG(2) << "AsyncCallback(" << name_ << ") thread start";
while (true) {
std::unique_lock<std::mutex> lock(mtx_);
cv_.wait(lock, [this] { return count_ > 0; });
if (!running_)
break;
2018-05-31 15:36:17 +03:00
if (callback_) {
for (auto &&data : datas_) {
callback_(data);
}
}
2018-05-31 10:39:42 +03:00
2018-05-31 15:36:17 +03:00
if (VLOG_IS_ON(2) && count_ > datas_.size()) {
VLOG(2) << "AsyncCallback(" << name_ << ") dropped "
<< (count_ - datas_.size());
2018-05-31 10:39:42 +03:00
}
count_ = 0;
2018-05-31 15:36:17 +03:00
datas_.clear();
2018-05-31 10:39:42 +03:00
}
VLOG(2) << "AsyncCallback(" << name_ << ") thread end";
}
MYNTEYE_END_NAMESPACE
#endif // MYNTEYE_INTERNAL_ASYNC_CALLBACK_IMPL_H_ NOLINT