Files
astros/src/runtime.c

101 lines
2.1 KiB
C

#include "runtime.h"
#include <sus/hashtable.h>
#include <sus/hashes.h>
#include <sus/ivector.h>
#include "thread_pool.h"
typedef struct recurring_callback_t {
long period;
long phase;
system_tick_t callback;
} recurring_callback_t;
static long _tick;
//hashtable_t<long, ivector_t<system_tick_t>*>
static hashtable_t *_future_callbacks;
//ivector_t<recurring_callback_t>
static ivector_t *_recurring_callbacks;
static thread_pool_t *callback_pool;
static void register_callback(long delay, system_tick_t callback)
{
long tick = delay + _tick;
ivector_t *vector = hashtable_get(_future_callbacks, tick);
if (!vector)
{
vector = ivector_create(sizeof(sizeof(system_tick_t)));
hashtable_add(_future_callbacks, tick, vector);
}
ivector_append(vector, callback);
}
static void handle_callbacks(ivector_t *callbacks)
{
size_t count = ivector_get_count(callbacks);
for (size_t i = 0; i < count; ++i)
{
system_tick_t *tick = ivector_get(callbacks, i);
//TODO: Dispatch work
}
}
static void register_recurring_callbacks()
{
size_t count = ivector_get_count(_recurring_callbacks);
for (size_t i = 0; i < count; ++i)
{
recurring_callback_t *callback = ivector_get(_recurring_callbacks, i);
long phase = _tick % callback->period;
if (phase != callback->phase)
continue;
register_callback(callback->period, callback->callback);
}
}
void runtime_init()
{
_tick = 0;
_future_callbacks = hashtable_create(hash_ptr, compare_ptr);
_recurring_callbacks = ivector_create(sizeof(recurring_callback_t));
}
void runtime_loop()
{
//Runtime loop
//Ticks every 10ms
//Systems request X tick delay callbacks
//Callbacks executed on separate threads
//Handle pending callbacks and register recurring
ivector_t *callbacks = hashtable_get(_future_callbacks, _tick);
if (callbacks)
{
handle_callbacks(callbacks);
hashtable_remove(_future_callbacks, _tick, NULL, NULL);
ivector_destroy(callbacks);
}
register_recurring_callbacks();
//Advance tick
++_tick;
//TODO: Delay and loop
}
void runtime_destroy()
{
hashtable_destroy_free(_future_callbacks, NULL, ivector_destroy);
ivector_destroy(_recurring_callbacks);
}