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

91 lines
2.3 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 <glog/logging.h>
#include <string>
#include <utility>
MYNTEYE_BEGIN_NAMESPACE
template <class Data>
2018-05-31 15:36:17 +03:00
AsyncCallback<Data>::AsyncCallback(
std::string name, callback_t callback, bool concat)
: name_(std::move(name)),
callback_(std::move(callback)),
count_(0),
concat_(concat) {
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-05-31 15:36:17 +03:00
if (!concat_) {
datas_.clear();
}
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