OpenCPN Partial API docs
Loading...
Searching...
No Matches
periodic_timer.cpp
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, see <https://www.gnu.org/licenses/>. *
16 **************************************************************************/
17
25
26PeriodicTimer::PeriodicTimer(std::chrono::milliseconds interval)
27 : m_interval(interval),
28 m_run_sts(1),
29 m_thread(std::thread([&] { Worker(); })) {}
30
31PeriodicTimer::~PeriodicTimer() {
32 if (m_run_sts == 1) {
33 Stop();
34 } else if (m_run_sts == 0) {
35 // ongoing stop() operation, wait until completed
36 std::unique_lock lock(m_mutex);
37 m_cond_var.wait_for(lock, m_interval, [&] { return m_run_sts < 0; });
38 }
39 if (m_thread.joinable()) m_thread.join();
40}
41
42void PeriodicTimer::Stop() {
43 m_run_sts = 0;
44 m_cond_var.notify_all();
45 std::unique_lock lock(m_mutex);
46 m_cond_var.wait_for(lock, m_interval, [&] { return m_run_sts < 0; });
47 lock.unlock();
48}
49
50void PeriodicTimer::Worker() {
51 while (m_run_sts > 0) {
52 std::unique_lock lock(m_mutex);
53 m_cond_var.wait_for(lock, m_interval, [&] { return m_run_sts <= 0; });
54 lock.unlock();
55 if (m_run_sts > 0) Notify();
56 }
57 m_run_sts = -1;
58 m_cond_var.notify_all();
59}
Manages reading the N2K data stream provided by some N2K gateways from the declared serial port.
Pure C++17 periodic timer.