1# libasync-loop and libasync-loop-cpp
2
3This library provides a general-purpose thread-safe message loop
4implementation declared in [async/loop.h](include/async/loop.h).
5It must be statically linked into clients that want to use this particular
6message loop implementation.  Note that clients can implement their own
7asynchronous dispatchers instead if they have more specialized needs.
8
9## Libraries
10
11- `libasync-loop.a` provides the loop implementation itself as declared in
12the following headers:
13    - [async-loop/loop.h](include/lib/async-loop/loop.h)
14
15- `libasync-loop-cpp.a` provides C++ wrappers:
16    - [async-loop/cpp/loop.h](include/lib/async-loop/cpp/loop.h)
17
18## Using the message loop
19
20`libasync-loop.a` provides a general-purpose thread-safe message loop
21implementation of an asynchronous dispatcher which you can use out of box
22unless you need something more specialized.
23
24See [async/loop.h](include/async/loop.h) for details.
25
26```c
27#include <lib/async-loop/loop.h>
28#include <lib/async/task.h>      // for async_post_task()
29#include <lib/async/time.h>      // for async_now()
30#include <lib/async/default.h>   // for async_get_default_dispatcher()
31
32static async_loop_t* g_loop;
33
34int main(int argc, char** argv) {
35    async_loop_create(&kAsyncLoopConfigAttachToCurrentThread, &g_loop);
36
37    do_stuff();
38
39    async_loop_run(g_loop, ZX_TIME_INFINITE, false);
40    async_loop_destroy(g_loop);
41    return 0;
42}
43
44void handler(async_dispatcher_t* async, async_task_t* task, zx_status_t status) {
45    printf("task deadline elapsed: status=%d", status);
46    free(task);
47
48    // This example doesn't have much to do, so just quit here.
49    async_loop_quit(g_loop);
50}
51
52zx_status_t do_stuff() {
53    async_dispatcher_t* async = async_get_default_dispatcher();
54    async_task_t* task = calloc(1, sizeof(async_task_t));
55    task->handler = handler;
56    task->deadline = async_now(async) + ZX_SEC(2);
57    return async_post_task(async, task);
58}
59```
60
61## Setting as the default async dispatcher
62
63If the `make_default_for_current_thread` configuration option is set to true
64and `libasync-default.so` is linked into the executable, the message loop
65will automatically register itself as the default dispatcher for the thread on
66which it is created.
67
68New threads started with `async_loop_start_thread()` will automatically have
69their default dispatcher set to the message loop regardless of the value of
70`make_default_for_current_thread`.
71