Blue Brain BioExplorer
Throttle.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015-2018, EPFL/Blue Brain Project
3  *
4  * Responsible Author: Daniel.Nachbaur@epfl.ch
5  *
6  * This file is part of Blue Brain BioExplorer <https://github.com/BlueBrain/BioExplorer>
7  *
8  * This library is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU Lesser General Public License version 3.0 as published
10  * by the Free Software Foundation.
11  *
12  * This library is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
15  * details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this library; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21 
22 #include "Throttle.h"
23 
24 namespace core
25 {
26 namespace
27 {
28 using namespace std::chrono;
29 auto now()
30 {
31  return high_resolution_clock::now();
32 }
33 auto elapsedSince(const time_point<high_resolution_clock>& last)
34 {
35  return duration_cast<milliseconds>(now() - last).count();
36 }
37 } // namespace
38 
39 void Throttle::operator()(const Throttle::Function& fn, const int64_t wait)
40 {
41  operator()(fn, fn, wait);
42 }
43 
45  const Throttle::Function& later, const int64_t wait)
46 {
47  time_point last;
48  {
49  std::lock_guard<std::mutex> lock(_mutex);
50  last = _last;
51  }
52  if (_haveLast && (elapsedSince(last) <= wait))
53  {
54  _timeout.clear();
55  auto delayed = [&_last = _last, &mutex = _mutex, later] {
56  std::lock_guard<std::mutex> lock(mutex);
57  later();
58  _last = now();
59  };
60  _timeout.set(delayed, wait);
61  }
62  else
63  {
64  fn();
65  _haveLast = true;
66  std::lock_guard<std::mutex> lock(_mutex);
67  _last = now();
68  }
69 }
70 } // namespace core
void operator()(const Function &fn, const int64_t wait=100)
Definition: Throttle.cpp:39
std::function< void()> Function
Definition: Throttle.h:35
void clear()
Definition: Timeout.cpp:55
void set(const std::function< void()> &func, const int64_t wait)
Definition: Timeout.cpp:31