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

which is actually incorrect:

using Base.Threads: Atomic, @threads

function want_to_return_early_PLEASE_DONT_USE_THIS(n, m)
    stop = Atomic{Bool}(false)
    result = Atomic{Bool}(false)
    @threads for i in 1:n
        stop[] && return
        if n == m
            result[] = true
            stop[] = true
            return
        end
    end
    return result[]
end

However, I don’t recommend this because:

  1. It relies on an undefined behavior of @threads; i.e., return terminates the basecase iteration.
  2. It introduces an atomic read stop[]. It may suppress some compiler optimization (even in x86). But I’m not super sure about this.

A better strategy is to chunk the iteration and check stop[] for each chunk (rather than each iteration).

2 Likes