Zth (libzth)
daemon_pattern.cpp

Pattern how to use and trigger a background daemon fiber.

#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;
}
}
zth_fiber(trigger)
// 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.
async trigger(&triggerSomeDaemon, 1);
while(!shutdown_flag) {
printf("daemon wakeup\n");
// ...and do some work.
triggerSomeDaemon.wait();
}
}
zth_fiber(someDaemon)
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))
{
async someDaemon();
zth::Gate gate(4);
async foo() << zth::passOnExit(gate);
async foo() << zth::passOnExit(gate);
async 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:757
Fiber-aware signal.
Definition: sync.h:456
void signal(bool queue=true, bool queueEveryTime=false) noexcept
Definition: sync.h:509
Convenient wrapper around struct timespec that contains a time interval.
Definition: time.h:52
constexpr bool isNegative() const noexcept
Definition: time.h:219
Convenient wrapper around struct timespec that contains an absolute timestamp.
Definition: time.h:527
static Timestamp now()
Definition: time.h:554
Makes the fiber pass the given gate upon exit.
Definition: async.h:229
int main_fiber(int argc, char **argv)
Definition: main.cpp:14
void nap(Timestamp const &sleepUntil)
Sleep until the given time stamp.
Definition: waiter.h:277
#define zth_fiber(...)
Prepare every given function to become a fiber by async.
Definition: async.h:765
#define async
Run a function as a new fiber.
Definition: async.h:789
#define UNUSED_PAR(name)
Definition: macros.h:79