Blue Brain BioExplorer
Timeout.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 "Timeout.h"
23 
24 namespace core
25 {
27 {
28  clear();
29 }
30 
31 void Timeout::set(const std::function<void()>& func, const int64_t wait)
32 {
33  if (_timeout.valid())
34  throw std::logic_error(
35  "Timeout cannot be set() while it is still active");
36 
37  _cleared = false;
38  _timeout =
39  std::async(std::launch::async, [&mutex = _mutex,
40  &condition = _condition,
41  &cleared = _cleared, wait, func] {
42  std::unique_lock<std::mutex> lock(mutex);
43  while (!cleared) // deals with spurious wakeups
44  {
45  if (condition.wait_for(lock, std::chrono::milliseconds(wait)) ==
46  std::cv_status::timeout)
47  {
48  func();
49  break;
50  }
51  }
52  });
53 };
54 
56 {
57  _cleared = true;
58  if (_timeout.valid())
59  {
60  {
61  std::unique_lock<std::mutex> lock(_mutex);
62  _condition.notify_one();
63  }
64  _timeout.get();
65  }
66 }
67 } // namespace core
void clear()
Definition: Timeout.cpp:55
void set(const std::function< void()> &func, const int64_t wait)
Definition: Timeout.cpp:31