# How to early return from inside a @threads loop

**URL:** https://discourse.julialang.org/t/how-to-early-return-from-inside-a-threads-loop/97457
**Category:** General Usage
**Tags:** question, parallel, multithreading, threads
**Created:** [April 14, 2023, 7:39am UTC](https://discourse.julialang.org/t/how-to-early-return-from-inside-a-threads-loop/97457 "2023-04-14T07:39:01Z")
**Posts on this page:** 1
**Showing post:** 7

<div class="post-metadata">

### Author: ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)
#### Post date: [April 14, 2023, 12:17pm UTC](https://discourse.julialang.org/t/how-to-early-return-from-inside-a-threads-loop/97457/7 "2023-04-14T12:17:01Z")

</div>

Another way, which is safe, is to use a lock:

```julia
julia> using ChunkSplitters
       function foo(data; nchunks=Threads.nthreads())
           lk = ReentrantLock()
           iwin, datawin = nothing, nothing
           Threads.@threads for (i_range, _) in chunks(data, nchunks)
               for i in i_range
                   if !isnothing(iwin)
                       break
                   end
                   # complex computation here
                   lock(lk) do 
                       if isnothing(iwin)
                           if data[i] == 10
                               iwin, datawin = i, data[i]
                           end
                       end
                   end
               end
           end
           return iwin, datawin
       end
foo (generic function with 1 method)

julia> a = foo(test)
(29, 10)

```

---

_[View the full topic](https://discourse.julialang.org/t/how-to-early-return-from-inside-a-threads-loop/97457)._
