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, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
18 **************************************************************************/
19
26
27PeriodicTimer::PeriodicTimer(std::chrono::milliseconds interval)
28 : m_interval(interval),
29 m_run_sts(1),
30 m_thread(std::thread([&] { Worker(); })) {}
31
32PeriodicTimer::~PeriodicTimer() {
33 if (m_run_sts == 1) {
34 Stop();
35 } else if (m_run_sts == 0) {
36 // ongoing stop() operation, wait until completed
37 std::unique_lock lock(m_mutex);
38 m_cond_var.wait_for(lock, m_interval, [&] { return m_run_sts < 0; });
39 }
40 if (m_thread.joinable()) m_thread.join();
41}
42
43void PeriodicTimer::Stop() {
44 m_run_sts = 0;
45 m_cond_var.notify_all();
46 std::unique_lock lock(m_mutex);
47 m_cond_var.wait_for(lock, m_interval, [&] { return m_run_sts < 0; });
48 lock.unlock();
49}
50
51void PeriodicTimer::Worker() {
52 while (m_run_sts > 0) {
53 std::unique_lock lock(m_mutex);
54 m_cond_var.wait_for(lock, m_interval, [&] { return m_run_sts <= 0; });
55 lock.unlock();
56 if (m_run_sts > 0) Notify();
57 }
58 m_run_sts = -1;
59 m_cond_var.notify_all();
60}
Manages reading the N2K data stream provided by some N2K gateways from the declared serial port.
Pure C++17 periodic timer.