I have a function that needs to schedule a task to the libuv event loop. My idea was to create a timer with 0ms timeout. I have tried the following code:
void myFunction() {
...
uv_timer_t* timer = new uv_timer_t();
uv_timer_init(uv_default_loop(), timer);
uv_timer_start(timer, [&](uv_timer_t* timer, int status) {
// Scheduled task
}, 0, 0);
}
This approach works well but the problem is, that the dynamically allocated timer will never be freed. I have tried freeing the timer in the callback, but that have led to segmentation fault:
void myFunction() {
...
uv_timer_t* timer = new uv_timer_t();
uv_timer_init(uv_default_loop(), timer);
uv_timer_start(timer, [&](uv_timer_t* timer, int status) {
// Scheduled task
delete timer;
}, 0, 0);
}
I have also tried to call uv_timer_stop(timer);
and uv_unref((uv_handle_t*) timer);
before the actual memory freeing, but the segmentation fault still remians.