# Inconsistent CPU utilisation in @threads loops

**URL:** <https://discourse.julialang.org/t/inconsistent-cpu-utilisation-in-threads-loops/110512>\
**Category:** Performance\
**Tags:** parallel, multithreading, threads, threading\
**Created:** [February 21, 2024, 12:49pm UTC](https://discourse.julialang.org/t/inconsistent-cpu-utilisation-in-threads-loops/110512 "2024-02-21T12:49:19Z")\
**Posts on this page:** 1\
**Showing post:** 18

<div class="post-metadata">

**Author:** ![carstenbauer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/carstenbauer/32/4981_2.png) [@carstenbauer](https://discourse.julialang.org/u/carstenbauer)\
**Post date:** [February 23, 2024, 8:41am UTC](https://discourse.julialang.org/t/inconsistent-cpu-utilisation-in-threads-loops/110512/18 "2024-02-23T08:41:02Z")

</div>

> [@abraemer](#):
>
> Can you clarify what is the difference between using `@threads` and `tforeach`?

Apart from the obvious (one is a loop macro the other one isn’t), `tforeach` gives you

- load balancing by default (it creates `2*nthreads()` tasks by default)
- more control over the “chunking”, that is, how the interval is divided into tasks (`@threads :dynamic/:static` always creates `nthreads()` tasks)

We want to add more features, like new schedulers, perhaps automatic pinning of threads, and more in the future. As for the “macro API”, it gives us some flexibility to make some patterns, like using TLS, a bit simpler (although we generally prefer the higher order function API).

OhMyThreads.jl also supports reductions, which `@threads` doesn’t (although `@distributed` does for multiprocessing). The `@threaded` macro will automatically expand to `tmapreduce` (rather than `tforeach`) if you provide a `reducer` argument, e.g.

```julia
julia> @threaded reducer=(+) for i in 1:3
           sin(i)
       end
1.8918884196934453

```

But now it’s time for me to stop (1) promoting our package and (2) derailing this thread any further. 🙂

---

_[View the full topic](https://discourse.julialang.org/t/inconsistent-cpu-utilisation-in-threads-loops/110512)._
