[erlang-questions] Static callback in NIF

Roger Lipscombe roger@REDACTED
Thu Jun 30 13:01:52 CEST 2016


As I understand it, if you're using enif_send from a background
thread, you should allocate a fresh environment for that case, using
enif_alloc_env:

    ErlNifEnv *msg_env = enif_alloc_env();
    ERL_NIF_TERM a_moo = enif_make_atom(msg_env, "moo");

    enif_send(NULL, &m_parentPid, msg_env, a_moo);
    enif_free_env(msg_env);

You can keep the pid around between threads, though:

    ErlNifPid parentPid;
    if (!enif_get_local_pid(env, argv[0], &m_parentPid))
        return enif_make_badarg(env);


On 30 June 2016 at 10:04, Sergej Jurečko <sergej.jurecko@REDACTED> wrote:
>
> On 29 Jun 2016, at 23:51, Igor Clark <igor.clark@REDACTED> wrote:
>
> Coming the other way works fine too, but relies on a C function callback
> which gets called when the hardware has a message for me. Right now I just
> have a static function in the NIF C code which I pass to the library. I
> create a static ErlNifEnv on NIF load() which I keep around and use in the
> callback to send messages to a specified erlang Pid, passed in via
> enif_get_local_pid() in another NIF function and also stored statically.
> This works a treat, but I'm feeling some pretty strong dread that it's very
> much the wrong way to do things, and asking for scheduler
> headaches/explosions.
>
>
> If there is a better way of doing this I haven't found it and I've spent a
> lot of time in NIF's. An issue might be if you end up using the same
> environment variable across multiple threads.
>
> Sergej
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list