79 lines
2.0 KiB
C
79 lines
2.0 KiB
C
|
// 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>
|
||
|
AsyncCallback<Data>::AsyncCallback(std::string name, callback_t callback)
|
||
|
: name_(std::move(name)), callback_(std::move(callback)), count_(0) {
|
||
|
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_);
|
||
|
data_ = data;
|
||
|
++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;
|
||
|
|
||
|
if (callback_)
|
||
|
callback_(data_);
|
||
|
|
||
|
if (VLOG_IS_ON(2) && count_ > 1) {
|
||
|
VLOG(2) << "AsyncCallback(" << name_ << ") dropped " << (count_ - 1);
|
||
|
}
|
||
|
count_ = 0;
|
||
|
}
|
||
|
VLOG(2) << "AsyncCallback(" << name_ << ") thread end";
|
||
|
}
|
||
|
|
||
|
MYNTEYE_END_NAMESPACE
|
||
|
|
||
|
#endif // MYNTEYE_INTERNAL_ASYNC_CALLBACK_IMPL_H_ NOLINT
|