Add another timer to an already running loop

Given the following program -

#include <iostream>
#include <uv.h>

int main()
{
    uv_loop_t loop;
    uv_loop_init(&loop);

    std::cout << "Libuv version: " << UV_VERSION_MAJOR << "."
              << UV_VERSION_MINOR << std::endl;

    int r = 0;

    uv_timer_t t1_handle;
    r = uv_timer_init(&loop, &t1_handle);
    uv_timer_start(&t1_handle,
      [](uv_timer_t *t) { std::cout << "Timer1 called\n"; }, 0, 2000);

    uv_run(&loop, UV_RUN_DEFAULT);

    // second timer
    uv_timer_t t2_handle;
    r = uv_timer_init(&loop, &t2_handle);
    uv_timer_start(&t2_handle,
      [](uv_timer_t *t) { std::cout << "Timer2 called\n"; }, 0, 1000);

    uv_loop_close(&loop);
}

The second timer descriptor never starts in a loop, because the loop is already running, and "Timer2 called" is never printed. So I tried to temporarily stop the loop after starting, and then add a second timer -

....
uv_run(&loop, UV_RUN_DEFAULT);

// some work

uv_stop(&loop);
// now add second timer
uv_run(&loop, UV_RUN_DEFAULT); // run again
....

But this did not work again, perhaps because later lines will not be executed after the 1st cycle starts with a repeating timer. So, how do I add a new timer descriptor to an already running uvloop?

+4
source share
1 answer

, , . , uv_stop uv_run, uv_run . , , . , , Timer1. .

#include <iostream>
#include <uv.h>

int main() {
  uv_loop_t loop;
  uv_loop_init(&loop);

  std::cout << "Libuv version: " << UV_VERSION_MAJOR << "." << UV_VERSION_MINOR
            << std::endl;

  int r = 0;

  uv_timer_t t1_handle;
  r = uv_timer_init(&loop, &t1_handle);
  *(bool *)t1_handle.data = true; // need to stop the loop
  uv_timer_start(&t1_handle,
                 [](uv_timer_t *t) {
                   std::cout << "Timer1 called\n";
                   bool to_stop = *(bool *)t->data;
                   if (to_stop) {
                     std::cout << "Stopping loop and resetting the flag\n";
                     uv_stop(t->loop);
                     *(bool *)t->data = false; // do not stop the loop again
                   }
                 },
                 0, 2000);
  uv_run(&loop, UV_RUN_DEFAULT);
  std::cout << "After uv_run\n";

  // second timer
  uv_timer_t t2_handle;
  r = uv_timer_init(&loop, &t2_handle);
  uv_timer_start(&t2_handle,
                 [](uv_timer_t *t) { std::cout << "Timer2 called\n"; }, 0,
                 1000);
  std::cout << "Start loop again\n";
  uv_run(&loop, UV_RUN_DEFAULT);

  uv_loop_close(&loop);
}

,

Libuv version: 1.9
Timer1 called
Stopping loop and resetting the flag
After uv_run
Start loop again
Timer2 called
Timer2 called
Timer1 called
Timer2 called
Timer2 called
Timer1 called
+2

Source: https://habr.com/ru/post/1657188/


All Articles