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

**URL:** <https://discourse.julialang.org/t/is-there-a-way-to-return-from-a-function-from-within-a-thread/35656>\
**Category:** General Usage\
**Tags:** parallel, threads\
**Created:** [March 6, 2020, 6:39pm UTC](https://discourse.julialang.org/t/is-there-a-way-to-return-from-a-function-from-within-a-thread/35656 "2020-03-06T18:39:07Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![tkf](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tkf/32/17635_2.png) [@tkf](https://discourse.julialang.org/u/tkf)\
**Post date:** [June 22, 2020, 7:36am UTC](https://discourse.julialang.org/t/is-there-a-way-to-return-from-a-function-from-within-a-thread/35656/7 "2020-06-22T07:36:25Z")

</div>

> [@tkf](#):
>
> Just to be clear, it’s not possible to terminate `@threads for` early, at least for now.

which is actually incorrect:

```julia
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).

---

_[View the full topic](https://discourse.julialang.org/t/is-there-a-way-to-return-from-a-function-from-within-a-thread/35656)._
