• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1Advanced event loops
2====================
3
4libuv provides considerable user control over event loops, and you can achieve
5interesting results by juggling multiple loops. You can also embed libuv's
6event loop into another event loop based library -- imagine a Qt based UI, and
7Qt's event loop driving a libuv backend which does intensive system level
8tasks.
9
10Stopping an event loop
11~~~~~~~~~~~~~~~~~~~~~~
12
13``uv_stop()`` can be used to stop an event loop. The earliest the loop will
14stop running is *on the next iteration*, possibly later. This means that events
15that are ready to be processed in this iteration of the loop will still be
16processed, so ``uv_stop()`` can't be used as a kill switch. When ``uv_stop()``
17is called, the loop **won't** block for i/o on this iteration. The semantics of
18these things can be a bit difficult to understand, so let's look at
19``uv_run()`` where all the control flow occurs.
20
21.. rubric:: src/unix/core.c - uv_run
22.. literalinclude:: ../../../src/unix/core.c
23    :linenos:
24    :lines: 304-324
25    :emphasize-lines: 10,19,21
26
27``stop_flag`` is set by ``uv_stop()``. Now all libuv callbacks are invoked
28within the event loop, which is why invoking ``uv_stop()`` in them will still
29lead to this iteration of the loop occurring. First libuv updates timers, then
30runs pending timer, idle and prepare callbacks, and invokes any pending I/O
31callbacks. If you were to call ``uv_stop()`` in any of them, ``stop_flag``
32would be set. This causes ``uv_backend_timeout()`` to return ``0``, which is
33why the loop does not block on I/O. If on the other hand, you called
34``uv_stop()`` in one of the check handlers, I/O has already finished and is not
35affected.
36
37``uv_stop()`` is useful to shutdown a loop when a result has been computed or
38there is an error, without having to ensure that all handlers are stopped one
39by one.
40
41Here is a simple example that stops the loop and demonstrates how the current
42iteration of the loop still takes places.
43
44.. rubric:: uvstop/main.c
45.. literalinclude:: ../../code/uvstop/main.c
46    :linenos:
47    :emphasize-lines: 11
48
49