# Need help understanding how to run a for loop in parallel

**URL:** https://discourse.julialang.org/t/need-help-understanding-how-to-run-a-for-loop-in-parallel/43739
**Category:** General Usage
**Tags:** parallel
**Created:** [July 27, 2020, 2:51am UTC](https://discourse.julialang.org/t/need-help-understanding-how-to-run-a-for-loop-in-parallel/43739 "2020-07-27T02:51:13Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![iamanoob](https://avatars.discourse-cdn.com/v4/letter/i/43a26b/32.png) [@iamanoob](https://discourse.julialang.org/u/iamanoob)
#### Post date: [July 27, 2020, 2:51am UTC](https://discourse.julialang.org/t/need-help-understanding-how-to-run-a-for-loop-in-parallel/43739/1 "2020-07-27T02:51:13Z")

</div>

Hello,

I am writing a huge program and given the amount of time required to perform the whole thing, i would like to use some parallel computation, however, i don’t understand how to implement it.

let’s say i have this piece of code :

> function dummy(a)  
> for i in 1:100  
> a=a+1  
> end  
> return a  
> end

> for i in 1:20  
> dummy(i)  
> end

my question is : how can i ask my computer to compute the second for loop in parallel. For example use 4cores/threads to do the for loop 4 steps at a time ?

i tried using @parallel and @thread before the for loop, but i always get an error

Thanks in advance

---

<div class="post-metadata">

### Author: ![StevenSiew](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevensiew/32/218393_2.png) [@StevenSiew](https://discourse.julialang.org/u/StevenSiew)
#### Post date: [July 27, 2020, 3:16am UTC](https://discourse.julialang.org/t/need-help-understanding-how-to-run-a-for-loop-in-parallel/43739/2 "2020-07-27T03:16:24Z")

</div>

```julia
function dummy(a)
    b = copy(a)
    for i in 1:100
        b=b+1
    end
    return b
end

You optimize it to
function dummy2(a)
    return a + 100
end

Then you do this in parallel
for i in 1:20
    i+100
end

Which gets optimized to
120

```

---

<div class="post-metadata">

### Author: ![hendri54](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hendri54/32/9621_2.png) [@hendri54](https://discourse.julialang.org/u/hendri54)
#### Post date: [July 27, 2020, 11:54am UTC](https://discourse.julialang.org/t/need-help-understanding-how-to-run-a-for-loop-in-parallel/43739/3 "2020-07-27T11:54:15Z")

</div>

```julia
# test1.jl
function dummy(a)
    for i in 1:100
      a=a+1
    end
    return a
end

Threads.@threads for i = 1 : 20
    println(Threads.threadid());
    dummy(i);
end

```

```julia
julia> include("test1.jl")
2
6
5
4
2
4
[...]

```
