# Generating multithreaded functions?

**URL:** https://discourse.julialang.org/t/generating-multithreaded-functions/28717
**Category:** General Usage
**Created:** [September 13, 2019, 11:57am UTC](https://discourse.julialang.org/t/generating-multithreaded-functions/28717 "2019-09-13T11:57:11Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Sheemon7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sheemon7/32/10277_2.png) [@Sheemon7](https://discourse.julialang.org/u/Sheemon7)
#### Post date: [September 13, 2019, 11:57am UTC](https://discourse.julialang.org/t/generating-multithreaded-functions/28717/1 "2019-09-13T11:57:11Z")

</div>

Is it possible to somehow generate functions with a multithreaded for-loop with @threads macro (or any other construct with the same fuctionality)?

The straightforward way fails

```julia
julia> @generated function f(x::Integer)
       quote
           @threads for i = 1:x
               println(i)
           end
       end
   end

julia> f(5)
ERROR: generated function body is not pure. this likely means it contains a closure or comprehension.

```

---

<div class="post-metadata">

### Author: ![sdanisch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sdanisch/32/1406_2.png) [@sdanisch](https://discourse.julialang.org/u/sdanisch)
#### Post date: [September 13, 2019, 12:27pm UTC](https://discourse.julialang.org/t/generating-multithreaded-functions/28717/2 "2019-09-13T12:27:22Z")

</div>

Would it be possible to make the inner function generated?  
E.g.

```julia
function f(x::Integer)
 @threads for i = 1:x
       f_generated_inner(x, i)
  end
end

```

---

<div class="post-metadata">

### Author: ![Sheemon7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sheemon7/32/10277_2.png) [@Sheemon7](https://discourse.julialang.org/u/Sheemon7)
#### Post date: [September 21, 2019, 2:16pm UTC](https://discourse.julialang.org/t/generating-multithreaded-functions/28717/3 "2019-09-21T14:16:46Z")

</div>

That’s a brilliant idea, however there is also an “initialization” part and “return” part of the function, which also depend on input types. I omitted these in the MWE above.
