An Erlang library with examples of NIFs (Native Implemented Functions) written in C, including functions that run on dirty schedulers.
NIFs are C functions that replace Erlang functions at runtime. They are useful when you need performance that Erlang alone cannot provide, or when you need to call existing C libraries.
The problem is that a regular NIF runs on an Erlang scheduler thread. If it takes too long, it blocks the scheduler and degrades the whole VM. Dirty schedulers solve this: Erlang provides a separate pool of threads for CPU-bound and I/O-bound work, and NIFs can opt in to run there instead.
This project shows how to set that up with a minimal, working example.
| Function | Arguments | Returns | Notes |
|---|---|---|---|
hello/0 |
none | hello_world |
Basic NIF, returns an atom |
add/2 |
two integers | their sum | Returns badarg for wrong types |
echo/1 |
binary | same binary | Zero-copy for large binaries |
cpu_bound/1 |
milliseconds | ok |
Busy-loops for N ms on a dirty CPU scheduler |
io_bound/1 |
milliseconds | ok |
Sleeps for N ms on a dirty I/O scheduler |
- Erlang/OTP 24 or later
- rebar3
- A C compiler (gcc or clang)
git clone https://github.com/Erlang-Brasil/nif
cd nif
make buildOr directly with rebar3:
rebar3 compileStart a shell with the library loaded:
make shellThen try the functions:
dirty_nif:hello().
%% => hello_world
dirty_nif:add(3, 4).
%% => 7
dirty_nif:echo(<<"hello">>).
%% => <<"hello">>
dirty_nif:cpu_bound(100).
%% => ok (after ~100ms of CPU work on a dirty scheduler)
dirty_nif:io_bound(100).
%% => ok (after ~100ms simulating blocking I/O)make eunit