diff --git a/src/timer.cpp b/src/timer.cpp index 9c37fa2..ed27891 100644 --- a/src/timer.cpp +++ b/src/timer.cpp @@ -7,8 +7,17 @@ uint64_t sc::timer::next_id = 0; std::mutex sc::timer::mutex; -sc::timer::timer(void(*callback)(union sigval), double time, bool repeat) - : _id {}, _time {time}, _repeat {repeat} +void sc::timer::callback(union sigval sv) { + timer* self = reinterpret_cast(sv.sival_ptr); + self->_expired_func(self, self->_context); +} + +sc::timer::timer(void(*expired_func)(timer*, void*), + double time, + bool repeat, + void* context) + : _id {}, _time {time}, _repeat {repeat}, + _expired_func {expired_func}, _context {context} { { std::lock_guard lock {mutex}; @@ -17,7 +26,7 @@ sc::timer::timer(void(*callback)(union sigval), double time, bool repeat) struct sigevent se; se.sigev_notify = SIGEV_THREAD; se.sigev_value.sival_int = 0; - se.sigev_value.sival_ptr = &_id; + se.sigev_value.sival_ptr = this; se.sigev_notify_function = callback; se.sigev_notify_attributes = nullptr; throw_if_min1_msg(timer_create(CLOCK_MONOTONIC, &se, &_tid), "could not create timer"); diff --git a/src/timer.hpp b/src/timer.hpp index f28c5ee..030be04 100644 --- a/src/timer.hpp +++ b/src/timer.hpp @@ -11,19 +11,28 @@ namespace sc { static std::mutex mutex; timer_t _tid; - uint64_t _id; - double _time; - bool _repeat; + uint64_t _id {}; + double _time {}; + bool _repeat {}; + void (*_expired_func)(timer* self, void* context); + void* _context {}; + + static void callback(union sigval); public: - timer(void(*callback)(union sigval), double time, bool repeat = false); + timer(void(*expired_func)(timer*, void*), + double time, + bool repeat, + void* context); ~timer(); + uint64_t id() const { return _id; } + double time() const { return _time; } + bool repeat() const { return _repeat; } + + bool is_armed() const; void time_left(struct itimerspec& cur_value) const; double time_left() const; - double time() const { return _time; } - bool is_armed() const; - bool repeat() const { return _repeat; } }; }