Pulp 1.88.0
Cross-platform audio plugin framework
Loading...
Searching...
No Matches
timer.hpp
Go to the documentation of this file.
1#pragma once
2
4#include <atomic>
5#include <cstdint>
6#include <functional>
7#include <memory>
8
9namespace pulp::events {
10
11// Timer bound to an EventLoop. Supports one-shot and repeating.
12//
13// Thread-safety + lifetime design:
14//
15// - Mutable state (active, generation, callback, interval, loop ref) lives
16// in a `shared_ptr<TimerImpl>` assigned exactly once at construction and
17// never reassigned. That single-assignment avoids racing on the
18// shared_ptr slot.
19// - Dispatch lambdas capture the shared_ptr by value. If the user-visible
20// Timer is destroyed while the EventLoop still has a queued dispatch,
21// the lambda's captured shared_ptr keeps TimerImpl alive until the
22// lambda finishes.
23// - stop() bumps `generation` so any in-flight dispatch whose captured gen
24// no longer matches returns early before calling the user callback.
25class Timer {
26public:
27 using Callback = std::function<void()>;
28
29 Timer(EventLoop& loop, Duration interval, Callback callback, bool repeating = true);
31
32 Timer(const Timer&) = delete;
33 Timer& operator=(const Timer&) = delete;
34
35 void start();
36 void stop();
37 bool is_active() const;
38
41
42private:
43 struct Impl;
44 std::shared_ptr<Impl> impl_;
45
46 // Static helpers keep the dispatch lambda free of `this` captures —
47 // the lambda only holds a shared_ptr<Impl> so post-destruction firing
48 // is safe.
49 static void schedule_next(std::shared_ptr<Impl> impl, std::uint64_t gen);
50};
51
52} // namespace pulp::events
Definition event_loop.hpp:22
Timer(EventLoop &loop, Duration interval, Callback callback, bool repeating=true)
Duration interval() const
bool is_active() const
void set_interval(Duration interval)
std::function< void()> Callback
Definition timer.hpp:27
Timer(const Timer &)=delete
Timer & operator=(const Timer &)=delete
Definition child_process_manager.hpp:18
Clock::duration Duration
Definition event_loop.hpp:17