# Sum result of Threads.foreach()

**URL:** https://discourse.julialang.org/t/sum-result-of-threads-foreach/76701
**Category:** General Usage
**Tags:** parallel
**Created:** [February 18, 2022, 3:17pm UTC](https://discourse.julialang.org/t/sum-result-of-threads-foreach/76701 "2022-02-18T15:17:12Z")
**Posts on this page:** 1
**Showing post:** 10

<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: [February 23, 2022, 7:12am UTC](https://discourse.julialang.org/t/sum-result-of-threads-foreach/76701/10 "2022-02-23T07:12:31Z")

</div>

Using atomics, locks, or channels is very likely not the right approach if you are using parallelism for speeding things up (unless you know what you are doing). I normally suggest using `Folds.sum` or `FLoops.@floop` for this. For more information, see: [A quick introduction to data parallelism in Julia](https://juliafolds.github.io/data-parallelism/tutorials/quick-introduction/)

That said, if “no package” is the hard requirement, you can write something like the following (untested):

```julia
topic_word_pairs::AbstractArray # assumption

basesize = cld(length(topic_word_pairs), Threads.nthreads())
chunks = Iterators.partition(topic_word_pairs, basesize)
sums_coherence = zeros(length(chunks))
nums_paris = zeros(Int, length(chunks))
@sync for (i, chunk) in enumerate(chunks)
    Threads.@spawn begin
        local sum_coherence = 0.0
        local num_pairs = 0
        for pair in chunk
            confirmation = calculate_confirmation(pair, model.corp)
            sum_coherence += confirmation
            num_pairs += 1
        end
        sums_coherence[i] = sum_coherence
        nums_pairs[i] = num_pairs
    end
end

sum_coherence = sum(sums_coherence)
num_pairs = sum(nums_pairs)

```

---

_[View the full topic](https://discourse.julialang.org/t/sum-result-of-threads-foreach/76701)._
