OpenCPN Partial API docs
wait_continue.h
Go to the documentation of this file.
1 /***************************************************************************
2  * Copyright (C) 2024 Alec Leamas *
3  * *
4  * This program is free software; you can redistribute it and/or modify *
5  * it under the terms of the GNU General Public License as published by *
6  * the Free Software Foundation; either version 2 of the License, or *
7  * (at your option) any later version. *
8  * *
9  * This program is distributed in the hope that it will be useful, *
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12  * GNU General Public License for more details. *
13  * *
14  * You should have received a copy of the GNU General Public License *
15  * along with this program; if not, write to the *
16  * Free Software Foundation, Inc., *
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
18  **************************************************************************/
19 
22 #ifndef WAIT_COND__
23 #define WAIT_COND__
24 
25 #include <cassert>
26 #include <chrono>
27 #include <condition_variable>
28 #include <mutex>
29 #include <thread>
30 
31 using namespace std::chrono_literals;
32 
33 class WaitContinue {
34 public:
36  WaitContinue() : is_waiting(false) {}
37 
38  WaitContinue& operator=(const WaitContinue) = delete;
39  WaitContinue(const WaitContinue&) = delete;
40 
42  void Continue() {
43  {
44  std::unique_lock lock(m_mutex);
45  is_waiting = false;
46  }
47  cv.notify_all();
48  }
49 
51  bool Wait(std::chrono::milliseconds timeout = 0s) {
52  std::unique_lock lock(m_mutex);
53  is_waiting = true;
54  auto t = std::chrono::high_resolution_clock::now() + timeout;
55  auto result = cv.wait_until(lock, t, [&]{ return !is_waiting; });
56  return true;
57  }
58 
60  void Wait(unsigned timeout_ms) {
61  Wait(std::chrono::milliseconds(timeout_ms));
62  }
63 
64 private:
65  bool is_waiting;
66  std::mutex m_mutex;
67  std::condition_variable cv;
68 };
69 
70 
71 #endif // WAIT_COND__
WaitContinue()
Default constructor, neither copyable nor assignable.
Definition: wait_continue.h:36
void Continue()
Release any threads blocked by Wait().
Definition: wait_continue.h:42
void Wait(unsigned timeout_ms)
Blocking wait for next Continue() or timeout (milliseconds)
Definition: wait_continue.h:60
bool Wait(std::chrono::milliseconds timeout=0s)
Blocking wait for next Continue() with optional timeout.
Definition: wait_continue.h:51