[erlang-questions] How long a NIF can block the Erlang BEAM?
Alceste Scalas
alceste@REDACTED
Tue Nov 23 11:10:02 CET 2010
On Tue, 23 Nov 2010 17:34:07 +0900, Kenji Rikitake
<kenji.rikitake@REDACTED> wrote:
> I wonder how long a NIF can block the Erlang BEAM. To put it another
> way, I want to know the maximum time allowed a NIF can run in the
> BEAM.
> One millisecond? Or 100 microseconds? Or even shorter?
>
> I am asking this to find out if I can run a fairly large operation of
> initialized a random number table in a NIF.
AFAIK, there are no hard limits: a NIF could block its Erlang
VM thread as long as needed --- but long-running NIFs will
disrupt the scheduling of other Erlang processes, and reduce
the responsiveness of unrelated applications running in the
same VM.
If you need to perform a long operation, and latency is not
an issue, you could spawn a dedicated NIF thread (using
enif_thread_create()), and let it send its return value to
the calling Erlang process (using enif_send()).
Thus, in your sfmt.erl file, you could do something like this:
init_gen_rand() ->
unexported_nif_init_gen_rand(self()),
receive
InitGenRandResult ->
InitGenRandResult
end.
This way, init_gen_rand/0 will still block until the PRNG is
ready, but its Erlang process will be scheduled away.
BTW: if you use this strategy, you may also need to perform
the PRNG initialization within the "on_load" function
(otherwise, you may need to protect the PRNG table with
locks...).
Regards,
--
Alceste Scalas <alceste@REDACTED>
More information about the erlang-questions
mailing list