Using a non-thread safe library in a NIF

There are two main reasons why C/C++ code might not be thread-safe:

  1. It is relying on global state (global variables, static inline variables, etc.)
  2. It is sharing data between (OS level) threads without proper checks that might prevent data races.

If (1) is the case, then there is very little you can do; it would require re-writing the original library. The best you might be able to do in this case is instead wrap the program in a separate executable and interact with it through a Port (or multiple ports, one per request or maybe a pool of them).

If (2) is the case, then you might be able to write your code in the way where data is not shared between threads, or where you add the proper checks on top.