Search code examples
cerlangerlang-nif

Erlang NIFs: Threads locking


Can NIF implementations use the regular C/C++ thread locking primitives or must they use the NIF APIs (enif_mutex_lock(..), enif_mutex_create(..), etc.)


Solution

  • From nif docs

    Threads and concurrency

    A NIF is thread-safe without any explicit synchronization as long as it acts as a pure function and only reads the supplied arguments. As soon as you write towards a shared state either through static variables or enif_priv_data you need to supply your own explicit synchronization. This includes terms in process independent environments that are shared between threads. Resource objects will also require synchronization if you treat them as mutable.

    So there is nothing forbidding you from doing whatever you want. You easily can write your own mutex/semafors and what not. And you can do it in C or C++ or Rust.

    That said, there is nothing preventing from braking everything. If you break anything you break it in whole VM. I would try to use standard Erlang ways of doing things, especially while paling with threads. Those are verified methods, and I haven't found any reason for replacing them with anything else.