Zth (libzth)
Loading...
Searching...
No Matches
daemon_pattern.cpp

Pattern how to use and trigger a background daemon fiber.

Pattern how to use and trigger a background daemon fiber.

/*
* SPDX-FileCopyrightText: 2019-2026 Jochem Rutgers
*
* SPDX-License-Identifier: CC0-1.0
*/
#include <zth>
static bool shutdown_flag = false;
// A generic trigger function that signals a zth::Signal every given interval.
// NOLINTNEXTLINE(performance-unnecessary-value-param)
void trigger(zth::Signal* s, zth::TimeInterval interval)
{
if(!s || interval.isNegative())
return;
while(!shutdown_flag) {
s->signal();
t += interval;
}
}
// A daemon just runs in the background. When another fiber does something that is relevant for the
// daemon, it signals a global zth::Signal. This wakes the daemon to perform its task.
static zth::Signal triggerSomeDaemon("someDaemon trigger");
void someDaemon()
{
// The daemon is an infinite loop, which ends waiting for its trigger signal. The wait for
// the signal is blocking. If a wakeup is required at some interval, start a timer to do
// this.
zth::fiber(trigger, &triggerSomeDaemon, 1);
while(!shutdown_flag) {
printf("daemon wakeup\n");
// ...and do some work.
triggerSomeDaemon.wait();
}
}
void foo()
{
printf("foo\n");
// Trigger the daemon, but only wake it once if triggered multiple times.
triggerSomeDaemon.signal();
zth::nap(0.5);
}
int main_fiber(int UNUSED_PAR(argc), char** UNUSED_PAR(argv))
{
zth::fiber(someDaemon);
zth::Gate gate(4);
zth::fiber(foo) << zth::passOnExit(gate);
zth::fiber(foo) << zth::passOnExit(gate);
zth::fiber(foo) << zth::passOnExit(gate);
gate.wait();
// Nap for a while, to show the interval trigger of the daemon.
zth::nap(10);
shutdown_flag = true;
return 0;
}
Fiber-aware barrier/gate.
Definition sync.h:1487
Fiber-aware signal.
Definition sync.h:692
void signal(bool queue=true, bool queueEveryTime=false) noexcept
Definition sync.h:745
Convenient wrapper around struct timespec that contains a time interval.
Definition time.h:55
constexpr bool isNegative() const noexcept
Definition time.h:241
Convenient wrapper around struct timespec that contains an absolute timestamp.
Definition time.h:568
static Timestamp now()
Definition time.h:595
int main_fiber(int argc, char **argv)
Definition main.cpp:11
void nap(Timestamp const &sleepUntil)
Sleep until the given time stamp.
Definition waiter.h:274
fiber_type< F >::fiber fiber(F &&f, Args &&... args)
Create and start a new fiber.
Definition async.h:1192
#define UNUSED_PAR(name)
Definition macros.h:78
Makes the fiber pass the given gate upon exit.
Definition async.h:266