# Conditional Multithreading

**URL:** <https://discourse.julialang.org/t/conditional-multithreading/32421>\
**Category:** General Usage\
**Tags:** multithreading\
**Created:** [December 18, 2019, 2:55am UTC](https://discourse.julialang.org/t/conditional-multithreading/32421 "2019-12-18T02:55:14Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![bjack205](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bjack205/32/7294_2.png) [@bjack205](https://discourse.julialang.org/u/bjack205)\
**Post date:** [December 18, 2019, 2:55am UTC](https://discourse.julialang.org/t/conditional-multithreading/32421/1 "2019-12-18T02:55:15Z")

</div>

Is there a way to enable/disable calls to Threads.@threads?

I’m developing an optimization solver, and when the problem is sufficiently small, using multi-threading hurts performance, and incurs allocations (my code doesn’t make any allocations until I wrap it in @threads). However, when the problem size grows and the individual operations being threaded become more computationally intensive (booting the arithmetic intensity) I get some good performance increases.

I’d like to be able to enable/disable multi-threading as a user-specified option. I can’t just restart Julia with JULIA\_NUM\_THREADS=1, since @threads still allocates memory and is slower than had I left it out. Can I do this using metaprogramming?

I know I can obviously just create duplicates of my functions and wrap some with @threads, but I’d rather avoid this if possible.

FYI: nearly all of my functions are trivially parallelizable, like this

```julia
function foo(vals, vars)
    for k in eachindex(vals)
        vals[k] = somefunction(vars[k])
    end
end

```

---

_[View the full topic](https://discourse.julialang.org/t/conditional-multithreading/32421)._
