[erlang-questions] question about NIF resources

Michael Santos <>
Mon Jan 3 14:45:08 CET 2011


On Mon, Jan 03, 2011 at 12:36:49PM +0100, Sverker Eriksson wrote:
> Michael Santos wrote:
>> The documentation is quite explicit about the behaviour of
>> enif_make_resource():
>>
>> "The term returned by enif_make_resource is totally opaque in nature. It
>> can be stored and passed between processses on the same node, but the
>> only real end usage is to pass it back as argument to a NIF.
>> <...>
>> Other operations such as matching or term_to_binary will have
>> unpredictable (but harmless) results."
>>
>> That's clear enough but I wonder if unpredictable behaviour is really
>> harmless or if I'm confused about how it works.  For example, with an
>> NIF wrapping malloc() [1] such as:
>>
>>   
> "Harmless" only in the sense that it will not crash your VM. You will  
> get an Erlangish result, but unpredictable. In other words: Dont do it!
>
> In current implementation, resource terms look and behave like empty  
> binaries. Matching is thus pointless. It's on the ToDo list to implement  
> matching.

Great!

> But even if the resource terms look alike, they are unique and there is  
> no bug leaking NIF resources (that I know of). A resource is released  
> (and destructor called) when the last reference is garbage collected.  
> The shell can fool you however, as it keeps a command history that can  
> retain terms even though you think the variables are forgotten. Test NIF  
> resource cleanup by running a test module and call  
> erlang:garbage_collect to force destructors to be called.

Works exactly as you said:

t() ->
    {ok,P} = mem:alloc(10),
    {ok,P} = mem:alloc(10),
    {ok,P} = mem:alloc(10),
    {ok,P} = mem:alloc(10),
    erlang:garbage_collect(),
    io:format("sleeping now ...~n"),
    timer:sleep(120000).


1> tt:t().
alloc: p=0x91eca30/0x918f630
alloc: p=0x91eca40/0x918f738
alloc: p=0x91eca50/0x918fd90
alloc: p=0x91ed008/0x918fdb8
cleanup: *p=0x91ed008/0x918fdb8
cleanup: *p=0x91eca50/0x918fd90
cleanup: *p=0x91eca40/0x918f738
cleanup: *p=0x91eca30/0x918f630
sleeping now ...

Thank you for the explanation!



More information about the erlang-questions mailing list