lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

I believe that the resources should be managed by code who created the task. Not by the task itself.
And in case of interruption it will be easy to release resources allocated by the task.
Moreover, we will gain control over the resources that the called code can use.

Here resource management using scope like approach using for statement:
in Lua 5.3
It enables to use auto and defer function for resource management.

It can be used for for coroutines:
Also a boilerplate code could be shorten by using macros.

for Lua 5.4 it can be modified to use to-be-closed vars:

But in this case you also have to call coroutine.close manually.

This approach hides to-be-closed variables from exposing to end users.
To-be-close variable are good only as internal mechanism, but not as general purpose.

And I believe it will cause a lot of bugs and problems in future if it will be widely applied.

On 15.10.2023 17:43, David Sicilia wrote:

1. There is a global table that maps coroutine --> stack-of-cleanup-tasks.
These tasks are pushed/popped from the stack as the coroutine runs.
2. Each cleanup task holds a reference to the cleanup function (I think
they can be weak if needed).
3. In a coroutine, use the pcall+call method whenever a resource is
created that needs to be cleaned up; the pcall wrapper will register
the cleanup function in the global cleanup stack.  If the pcall'd function
exits normally, the cleanup task will be popped and run.
4. The coroutine could have a __gc method that does the cleanup, just
by popping the cleanup tasks and running them.

This way, if the coroutine is suspended and its resources need to be
cleaned up, we either "close" it by running all of its cleanup routines
in reverse order, or we let it be GC'd, in which case the coroutine's
finalizer will do the same.