Manage resource reference counts with release and keep
mainResources use reference counting to prevent the BEAM GC from destroying memory while a NIF is still using it. The resource type provides .release() and .keep() methods.
Key Behaviors
release: Decrements the reference count.- By default, a resource created via
StructResource.create(...)is released on creation. This can be disabled with.release = falsein the options. - If a function takes a
beam.Resource(...)type as an argument, it is released at the end of the call unless the:nocleanflag is set in the function argument options.
- By default, a resource created via
keep: Increments the reference count.beam.getkeeps the resource by default. This can be disabled with.keep = falsein the options.
Warning: For wrapped datatypes that require cleanup (like pointers), do not use beam.get with .keep = false. This can cause a race condition where the pointer is dereferenced after another thread has performed cleanup.
Example:
pub fn release(resource: StructResource) void {
resource.release();
}
pub fn keep(resource: StructResource) void {
resource.keep();
}