# 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:** 6

<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:24am UTC](https://discourse.julialang.org/t/is-there-a-way-to-return-from-a-function-from-within-a-thread/35656/6 "2020-06-22T07:24:58Z")

</div>

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](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

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

```

then the parallel version is

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

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

```

---

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