Driver question

Raimo Niskanen raimo@REDACTED
Wed Aug 15 19:12:28 CEST 2001


Sean Hinde wrote:
> 
> Hi,
> 
> I want to do someting like this:
> 
> Allocate some storage in my driver, pass the data to erlang, and then, if
> the data goes out of scope at an erlang level have the storage automatically
> freed out of the driver by garbage collection.
> 
> Maybe driver binaries exhibit this effect already? Or do they need to be
> freed in the driver as well as Erlang?
> 

Yes they do. They might be exactly what you need. The driver binaries
are reference counted, and when you call driver_allocate_binary(),
refcnt is set to 1 (only the driver is holding the binary).

When you later call driver_output_binary(), refcnt is incremented to 2,
and note that the driver must not change the contents from now on, since
erlang processes now can see the data and depend on this. The driver
migth as well call driver_free_binary(), which just decrements refcnt.
Only when refcnt decrements to 0, the binary is actually freed.

Every erlang process that now receives the binary will increment refcnt,
and when the binary is garbage collected and found to be unused refcnt
is decremented and finaly freed by the last erlang processe that garbage
collects it.

A driver that implements the outputv() callback receives binaries in an
ErlIOVec. When it does not need the data anymore, driver_free_binary
must be used to free the binaries, or if driver_enq(), driver_deq() and
related (the queue interface) are used, they take care of the refcnt and
freeing.

> There is a part of the inet_drv where the refc value of the binary is
> checked to see if anyone else still needs it, which then frees it if no-one
> else does, but this still implies some cleanup routine run regularly in the
> driver.
> 

I guess that the trick in inet_drv is about reusing a buffer that has
not been sent to erlang, instead of actually freeing the memory and then
allocating a new buffer, which is rather expensive.

/ Raimo Niskanen, Erlang/OPT, Ericsson UAB



More information about the erlang-questions mailing list