rt/cxx/examples/once.cpp

40 lines
699 B
C++

#include <rt/once.hpp>
#include <rt/sem.hpp>
#include <rt/task.hpp>
#include <rt/trap.hpp>
#include <rt/assert.h>
#include <rt/atomic.h>
static rt::once once;
static rt::sem sem;
static rt_atomic_ulong x = 0;
static void fn(void)
{
rt_atomic_fetch_add(&x, 1, RT_ATOMIC_RELAXED);
}
static void oncer(void)
{
rt::task::drop_privilege();
once.call(fn);
sem.wait();
rt_assert(rt_atomic_load(&x, RT_ATOMIC_RELAXED) == 1,
"x has the wrong value");
rt::trap();
}
static void twicer(void)
{
rt::task::drop_privilege();
once.call(fn);
sem.post();
}
#define STACK_SIZE (RT_STACK_MIN * 2)
RT_TASK(oncer, STACK_SIZE, 0);
RT_TASK(twicer, STACK_SIZE, 0);