[erlang-questions] How to properly stop complicated async NIF resource.

Mikael Karlsson karlsson.rm@REDACTED
Wed Jul 17 19:39:42 CEST 2019

Hi Max,
I had a similar problem when interfacing towards the ALSA library for sound
generation on Linux, but it is probably much more simple than your case so
I am not sure it will help.
For every thread I have a peer gen_server that opens a handle in a resource
and starts the callback thread (I get events every 5 ms) in init/1 and
handle_continue/2 function . When the gen_server is shutdown and
terminate/2 is called I call the a nif to close the handle. The resource
itself is garbage collected by erlang (I think :-) ).
What I noticed was that I had to set the process_flag(trap_exit, true) in
order to have the terminate function called at supervisor:terminate_child/2
I am not sure what you are meaning with delayed destructor but if you need
a lot of time for complete destruction maybe you can orchestrate it from a
separately spawned erlang process that calls the proper nifs.

You can checkout my code at https://github.com/karlsson/xalsa , mainly
c_src/xalsa_nif.c and src/xalsa_server.erl

Best Regards

Den ons 17 juli 2019 kl 17:53 skrev Max Lapshin <max.lapshin@REDACTED>:

> Hi.
> We are writing NIF wrapper for OpenMAX — standard API for transcoding
> video on Android or Raspberry Pi.
> This API requires to launch separate thread (launched by library) and this
> thread receives some events from hardware. This thread wraps hardware
> events in erlang messages and sends them to owner process.  All this looks
> really cool and we have excellently working happy path of code.
> When whole resource is to be destroyed, we need to clean it properly,
> shutdown all opened hardware handlers. Right now we have to write
> complicated code on C in destructor that calls cond_wait, mutex_lock, etc.
> The same code in erlang is 100 times cleaner and easier, however in
> destructor we cannot write in erlang.  I cannot exit from destructor
> function and ask to continue destructing when separate thread will be
> activated by hardware.
> So it would be cool to continue having erlang vm even in destructor or
> make something like "delayed destructor" with "I promise to finish this
> destruction".
> Question is: is my problem well known or it is very specific?
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190717/6c467f7a/attachment.htm>

More information about the erlang-questions mailing list