Libuv
04 Jul 2023—uvBuf layout: post title: libuv date: 2023-07-04 comments: false categories: [ “” ] —
libuv is a multi-platform library that provides your programs with asynchronous capabilities through the use of an event loop. node.js has been the most mainstream usage of this library.
Today’s post will talk about this library and show some working examples.
Features
libuv provides a quite a set of features:
- Event loop
- Async file and network I/O
- File system events
- IPC
- Thread pool
- Signal handling
- High resolution clock
Event loop
When you’re programming in an event-driven environment, you need a medium that can transfer control over to your program when an event occurs. The event loop’s job is to do exactly this, running forever.
If you were to think about it in c-pseudo code, it might look something like this.
Watchers
The list of handles that can send us events, and signal our application are here:
These are the handles that we can register interest in; so the system will raise interesting events to us.
Get started
Before we get started, the libuv library needs to be installed along with the development files. In order to do this on my Debian machine, I’ll install the development and the runtime files.
libuv1 - asynchronous event notification library - runtime library
libuv1-dev - asynchronous event notification library - development files
Now, when we build an executable we need to link to the uv
library using -luv
. For the CMake test application that I’m writing with this article, I used:
Where uvtest
is the name of my application.
First program
The “hello, world” of event loops. We’ll allocate the event loop, run the loop, and then cleanup.
Idle
While our program is doing “nothing”, waiting for the next event we can register a function to execute. You’ll notice in this code that we’re using a uv_idle_t
rather than a uv_loop_t
(as above). Using uv_idle_t
provides us access to register an “idler” function.
The idle function, count_to_10
counts up until we exceed 10 and then calls uv_idle_stop
which is our exit.
Finishing up
This has just been an introduction to the absolute basics of libuv.