<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
</head>
<body text="#000000" bgcolor="#FFFFFF">
<div class="moz-cite-prefix">On 11/23/20 11:24 AM, José Valim wrote:<br>
</div>
<blockquote type="cite"
cite="mid:CAGnRm4+NP0yMiYFVEVzTbg0wAYLcv5v3Q0g_82HbZCE=oPcZiw@mail.gmail.com">
<meta http-equiv="content-type" content="text/html;
charset=windows-1252">
<div dir="ltr">
<div>Hi everyone,<br>
</div>
<div><br>
</div>
<div>We are working on some code that allocates large chunks of
memory inside a NIF and ties them to a resource (using
enif_alloc_resource + enif_make_resource). While running some
tests, I noticed that we were holding onto these resources for
longer than we wanted to, so we have added calls to
erlang:garbage_collect/1. In a nutshell, the code looks like
this:</div>
<div><br>
</div>
<div style="margin-left:40px">my_nif:function_allocates_large_memory(),</div>
<div style="margin-left:40px">erlang:garbage_collect(),</div>
<div style="margin-left:40px">my_nif:check_if_resource_has_been_destroyed().<br>
</div>
<div><br>
</div>
<div>In our runs, it seems that the resource has not yet been
destroyed in most cases. However, if we do add a sleep after
garbage collection, then the odds of it being destroyed
increases as we increase the sleep interval.</div>
<div><br>
</div>
<div>Is this correct? Even if the resource was garbage
collected, the destructor may not have been called? Or is this
actually a big in our software that we should look deeper
into?</div>
</div>
</blockquote>
Hi José,<br>
<br>
You are suppose to tie the lifetime of the resource to the lifetime
of an Erlang process to let the garbage collection happen more
naturally. That should make the problem disappear. An example of
making the garbage collection as fast as possible is at
<a class="moz-txt-link-freetext" href="https://gist.github.com/okeuday/dee991d580eeb00cd02c">https://gist.github.com/okeuday/dee991d580eeb00cd02c</a> (immediate_gc
module) but it is best to not use <span class="pl-en">erlang</span>:<span
class="pl-en">garbage_collect/0.<br>
<br>
Best Regards,<br>
Michael<br>
</span><br>
</body>
</html>