Using uv_close instead of uv_async_send for single use uv_async callbacks?

1.7k views Asked by At

My understanding is that the proper use of uv_async for a single use is the following:

  1. Allocate the uv_async_t handle;
  2. call uv_async_init on the allocated handle;
  3. call uv_async_send to schedule the callback;
  4. unregister the handle using uv_close;
  5. delete the uv_async_t handle in the close callback;

For example:

    uv_async_t *handle = (uv_async_t*)malloc(sizeof(uv_async_t));
    uv_async_init(&uvLoop, handle, [](uv_async_t *handle) { 
        // My async callback here
        uv_close((uv_handle_t*)handle, [](uv_handle_t* handle) {
            free(handle);
        });
    });
    uv_async_send(&asyncCb->uvAsync);

From what I gather, uv_close is called asynchronously in the uvLoop. Therefore, I am tempted to do the following to avoid queueing two callbacks in the event loop:

    uv_async_t *handle = (uv_async_t*)malloc(sizeof(uv_async_t));
    uv_async_init(&uvLoop, handle, nullptr);
    uv_close((uv_handle_t*)handle, [](uv_handle_t* handle) {
        // My async callback here
        free(handle);
    });

Is anyone else doing this, and is it considered safe?

1

There are 1 answers

1
saghul On BEST ANSWER

What is it you are tying to achieve? Do you need to use multiple threads? If so, that won't work since uv_close is not thread-safe.

If all you want is to schedule a callback in the future within the loop, check uv_idle_t. You could also use a queue and start / stop the handle as needed, instead of creating and destroying then.