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() { Stop(); }
33
34void PeriodicTimer::Stop() {
35 m_run_sts = 0;
36 m_cond_var.notify_all();
37 std::unique_lock lock(m_mutex);
38 m_cond_var.wait_for(lock, m_interval, [&] { return m_run_sts < 0; });
39 lock.unlock();
40 if (m_thread.joinable()) m_thread.join();
41}
42
43void PeriodicTimer::Worker() {
44 while (m_run_sts > 0) {
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 if (m_run_sts > 0) Notify();
49 }
50 m_run_sts = -1;
51 m_cond_var.notify_all();
52}
Manages reading the N2K data stream provided by some N2K gateways from the declared serial port.
Pure C++17 periodic timer.