ResourceContexts.jl icon indicating copy to clipboard operation
ResourceContexts.jl copied to clipboard

Thread safety

Open tkf opened this issue 4 years ago • 1 comments

Since

https://github.com/c42f/ResourceContexts.jl/blob/732a8cadbeb76e2dd5dfaed2ca244fe099d2f326/src/ResourceContexts.jl#L11-L12

is not protected by a lock, I'm guessing that the following pattern is not data-race-free?

function f()
    @context begin
        @sync begin
            @spawn readlines(@!(open("1.txt", "r")))
            @spawn readlines(@!(open("2.txt", "r")))
        end
    end
end

I just noticed it while reading the code and it's not causing a real issue to me. But I thought it is worth bringing it up (so that, e.g., users browsing the issue notice it).

tkf avatar Aug 29 '21 01:08 tkf

That's right, this would be a data race right now.

This isn't by design; I just wasn't considering the context being captured into multiple threads.

I wonder what to do here. Do we make it thread safe by default?

I realized there's a semi-related problem without even involving threads:

function f()
    @context begin
        @async readlines(@!(open("1.txt", "r")))
    end
    # cleanup never called !?!
end

c42f avatar Sep 07 '21 09:09 c42f