Skip to content

Iterators and resource management #22466

@davidanthoff

Description

@davidanthoff

This is a problem I have in Query.jl: I sometimes want to iterate things where I am acquiring some resource in the start method that needs to be explicitly freed later on. For example I might open a file in the start method, and at some point I'd like to close it again. I could close it in the last call to the done function, but I can't be sure that it will ever be called, so that is really kind of sloppy.

One solution might be that a normal for loop gets lowered to something like this:

s = start(source)
try
    while !done(source, s)
        v, s = next(source, s)
        # Loop body
    end
finally
    dispose(source, s)
end

With a default implementation of dispose:

@inline dispose(a,b) = nothing

And then I could add a method to dispose for my type that closes say a file that I opened in start.

That design would probably only work if the compiler was able to detect cases where the whole try...finalize block did nothing (i.e. where the finally block didn't do anything) and then was able to remove the whole try...finally construct. I assume otherwise it would cause too much of a performance problem.

In any case, even if my idea here doesn't work, it would be good to have some resource management story for iterators.

Probably relates to #18823 and #11207.

Metadata

Metadata

Assignees

No one assigned

    Labels

    collectionsData structures holding multiple items, e.g. sets

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions