Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NIF

An Erlang library with examples of NIFs (Native Implemented Functions) written in C, including functions that run on dirty schedulers.

Background

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.

Functions

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

Requirements

  • Erlang/OTP 24 or later
  • rebar3
  • A C compiler (gcc or clang)

Build

git clone https://github.com/Erlang-Brasil/nif
cd nif
make build

Or directly with rebar3:

rebar3 compile

Usage

Start a shell with the library loaded:

make shell

Then 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)

Tests

make eunit

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages