# OncePerTask case

**URL:** <https://discourse.julialang.org/t/oncepertask-case/134719>\
**Category:** General Usage\
**Created:** [December 24, 2025, 8:11am UTC](https://discourse.julialang.org/t/oncepertask-case/134719 "2025-12-24T08:11:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![yolhan\_mannes](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yolhan_mannes/32/220485_2.png) [@yolhan\_mannes](https://discourse.julialang.org/u/yolhan_mannes)\
**Post date:** [December 24, 2025, 8:11am UTC](https://discourse.julialang.org/t/oncepertask-case/134719/1 "2025-12-24T08:11:47Z")

</div>

Hello, sorry I keep forgetting how to do this :

```julia-auto
function main()
   n = UInt128(10^7)
   input ::Vector{UInt128} = collect(0:n-1)
   result = OncePerTask() do
       Ref(UInt128(0))
   end
   Threads.@threads for i in input
       result()[] += i*i
   end
   return result
end

```

how to collect after that ? I know, people should use OhMyThreads.jl, but this should work right ? and be somewhat equivalent to

```julia-auto
function main()
   n = UInt128(10^7)
   input ::Vector{UInt128} = collect(0:n-1)
   result = Vector{UInt128}(undef,16)
   it = Iterators.partition(1:n,cld(n,16))
   @sync for (id,I) in enumerate(it)
       Threads.@spawn begin
           s ::UInt128 = 0
           for i in I
               ini = input[i]
               s += ini*ini
           end
           result[id] = s
       end
   end
   return sum(result)
end

```

---

<div class="post-metadata">

**Author:** ![yolhan\_mannes](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yolhan_mannes/32/220485_2.png) [@yolhan\_mannes](https://discourse.julialang.org/u/yolhan_mannes)\
**Post date:** [December 24, 2025, 11:10am UTC](https://discourse.julialang.org/t/oncepertask-case/134719/2 "2025-12-24T11:10:54Z")

</div>

Found it back

```julia-auto
function main2()
   n = UInt128(10^7)
   input = 0:n-1
   res_chan = Channel{Base.RefValue{UInt128}}(Inf)
   result = Base.OncePerTask() do
       r = Ref(UInt128(0))
       put!(res_chan, r)
       return r
   end
   @sync begin
       Threads.@threads for i in input
           result()[] += i*i
       end
   end
   close(res_chan)
   return sum(r[] for r in res_chan)
end

```
