From 3dc21c0378e672f6df1f96da48e49ec845a8a211 Mon Sep 17 00:00:00 2001 From: John Zhao Date: Wed, 11 Jul 2018 15:04:14 +0800 Subject: [PATCH] Limit max data size for async callback --- src/device/device.cc | 5 +++-- src/internal/async_callback.h | 5 +++-- src/internal/async_callback_impl.h | 8 +++++--- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/device/device.cc b/src/device/device.cc index a672ffc..cbfb64c 100644 --- a/src/device/device.cc +++ b/src/device/device.cc @@ -335,7 +335,7 @@ void Device::SetStreamCallback( if (async) stream_async_callbacks_[stream] = std::make_shared( - to_string(stream), callback); + to_string(stream), callback); // max_data_size = 1 } else { stream_callbacks_.erase(stream); stream_async_callbacks_.erase(stream); @@ -347,7 +347,8 @@ void Device::SetMotionCallback(motion_callback_t callback, bool async) { if (callback) { if (async) motion_async_callback_ = - std::make_shared("motion", callback, true); + std::make_shared("motion", callback, 1000); + // will drop old motion datas after callback cost > 2 s (1000 / 500 Hz) } else { motion_async_callback_ = nullptr; } diff --git a/src/internal/async_callback.h b/src/internal/async_callback.h index 43944d2..c00f4b4 100644 --- a/src/internal/async_callback.h +++ b/src/internal/async_callback.h @@ -31,7 +31,8 @@ class AsyncCallback { public: using callback_t = std::function; - AsyncCallback(std::string name, callback_t callback, bool concat = false); + AsyncCallback( + std::string name, callback_t callback, std::size_t max_data_size = 0); ~AsyncCallback(); void PushData(Data data); @@ -50,8 +51,8 @@ class AsyncCallback { std::thread thread_; std::uint32_t count_; - bool concat_; std::vector datas_; + std::size_t max_data_size_; }; MYNTEYE_END_NAMESPACE diff --git a/src/internal/async_callback_impl.h b/src/internal/async_callback_impl.h index 23f8ead..3c502b3 100644 --- a/src/internal/async_callback_impl.h +++ b/src/internal/async_callback_impl.h @@ -24,11 +24,11 @@ MYNTEYE_BEGIN_NAMESPACE template AsyncCallback::AsyncCallback( - std::string name, callback_t callback, bool concat) + std::string name, callback_t callback, std::size_t max_data_size) : name_(std::move(name)), callback_(std::move(callback)), count_(0), - concat_(concat) { + max_data_size_(max_data_size) { VLOG(2) << __func__; running_ = true; thread_ = std::thread(&AsyncCallback::Run, this); @@ -51,8 +51,10 @@ AsyncCallback::~AsyncCallback() { template void AsyncCallback::PushData(Data data) { std::lock_guard _(mtx_); - if (!concat_) { + if (max_data_size_ <= 0) { datas_.clear(); + } else if (max_data_size_ == datas_.size()) { // >= 1 + datas_.erase(datas_.begin()); } datas_.push_back(data); ++count_;