Is there a way to return from a function from within a thread?

Just to be clear, it’s not possible to terminate @threads for early, at least for now. You need to build @threads-like iteration support on top of @spawn for this.

If you are curious, I think the simplest example code is Threads.foreach:
https://github.com/JuliaLang/julia/pull/34543/files#diff-c3a80cb045a6bb5c1884c379f4fab047


But, if you just want to use something like a for loop without implementing it, you can also just use Transducers.jl. If you have a sequential version

y = nothing
for x in xs
    z = process(x)
    if should_terminate(z)
        y = z
        break
    end
end

then the parallel version is

reduce(Map(identity), xs; init = nothing) do _, x
    y = process(x)
    if should_terminate(y)
        return Reduce(y)  # equivalent to `break`
    else
        return nothing
    end
end

or equivalently

reduce(right, Map(process) |> ReduceIf(should_terminate), xs; init = nothing)
2 Likes