libuv
libuv is a multi-platform library for asynchronous I/O. It was primarily
developed for use by Node.js, but it's also used by Luvit, Julia, pyuv,
and others.
It supports Windows IOCP, epoll, kqueue, and Solaris event ports. It
also provides the event loop and callback-based asynchrony. The library
is written in C and has bindings to various languages.
Features
1. Cross-Platform Abstraction: It hides different low-level OS
notification systems—like epoll on Linux, kqueue on macOS, and IOCP on
Windows—behind a single uniform API.
2. Event Loop: It manages an event loop that runs callbacks when
tasks (like network requests or timers) finish, keeping applications
fast and non-blocking.
3. Thread Pool: It provides an internal thread pool to handle
operations that do not have native asynchronous support from the
operating system, such as file system tasks.
Example
1. Create a Timer
$ sudo apt-get install libuv1-dev Install libuv
#include <stdio.h>
#include <uv.h>
// This function runs when the timer finishes
void on_timer(uv_timer_t* handle) {
printf("Timer finished!\n");
}
int main() {
uv_loop_t *loop = uv_default_loop();
uv_timer_t timer;
uv_timer_init(loop, &timer);
// Start the timer: call on_timer after 1000ms (1 second), do not repeat
uv_timer_start(&timer, on_timer, 1000, 0);
// Run the event loop
uv_run(loop, UV_RUN_DEFAULT);
// Clean up
uv_loop_close(loop);
return 0;
}