# Repetitive Matrix Addition using Threads

**URL:** https://discourse.julialang.org/t/repetitive-matrix-addition-using-threads/85292
**Category:** General Usage
**Tags:** multithreading
**Created:** [August 4, 2022, 10:22am UTC](https://discourse.julialang.org/t/repetitive-matrix-addition-using-threads/85292 "2022-08-04T10:22:34Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Amol\_H](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/amol_h/32/34413_2.png) [@Amol\_H](https://discourse.julialang.org/u/Amol_H)
#### Post date: [August 4, 2022, 10:22am UTC](https://discourse.julialang.org/t/repetitive-matrix-addition-using-threads/85292/1 "2022-08-04T10:22:34Z")

</div>

Greetings All,

Please suggest how to reduce the Matrix addition using @threads. In the following example, I am trying to add 10x10 ones matrix 100 times. Ideally, the sum of all elements of the final matrix should be 10000. I am unable to run this in parallel as because of race conditions it is giving the wrong result. I will really appreciate any help in this regard.

```julia
#!/usr/bin/julia

using LinearAlgebra, Base.Threads

function TestReduction()

   X = zeros(10,10);
   Y = ones(10,10);
 
   Threads.@threads for i = 1:100
      X = X + Y;
   end

   println("Sum(X) = " , sum(X));
end 

TestReduction()

```

---

<div class="post-metadata">

### Author: ![ericphanson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ericphanson/32/215186_2.png) [@ericphanson](https://discourse.julialang.org/u/ericphanson)
#### Post date: [August 4, 2022, 11:30am UTC](https://discourse.julialang.org/t/repetitive-matrix-addition-using-threads/85292/2 "2022-08-04T11:30:37Z")

</div>

One option:

```julia
julia> using ThreadsX

julia> X = zeros(10,10);

julia> Y = ones(10,10);

julia> ThreadsX.map(+, X, Y)
10×10 Matrix{Float64}:
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0

julia> ThreadsX.mapreduce(+, +, X, Y)
100.0

```
