# Best way to parallelize for loop with given thread number

**URL:** <https://discourse.julialang.org/t/best-way-to-parallelize-for-loop-with-given-thread-number/131141>\
**Category:** New to Julia\
**Created:** [July 28, 2025, 5:50pm UTC](https://discourse.julialang.org/t/best-way-to-parallelize-for-loop-with-given-thread-number/131141 "2025-07-28T17:50:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Leibniz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/leibniz/32/217959_2.png) [@Leibniz](https://discourse.julialang.org/u/Leibniz)\
**Post date:** [July 28, 2025, 5:50pm UTC](https://discourse.julialang.org/t/best-way-to-parallelize-for-loop-with-given-thread-number/131141/1 "2025-07-28T17:50:29Z")

</div>

Greetings,

what is the most efficient way to parallelize a for loop if I only want to use `n` of `N` active global threads?

The way I understand it,

```julia
Threads.@threads for it in 1:nthreads

```

will use all available threads which might not be optimal.  
I set `export JULIA_NUM_THREADS=10` as an environment variable such that when I run my script in VSCode, the REPL will automatically be launched with 10 threads.  
In the script however, I would like to be able to say

```julia
threads_to_use = 5
my_func(threads_to_use)

```

where `my_func` runs an expensive for-loop that should be parallelized.

The AI overlord informed me of so-called Semaphores, but I have not found much documentation about their usage.

Regards!

---

<div class="post-metadata">

**Author:** ![photor](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/photor/32/14343_2.png) [@photor](https://discourse.julialang.org/u/photor)\
**Post date:** [July 29, 2025, 3:19am UTC](https://discourse.julialang.org/t/best-way-to-parallelize-for-loop-with-given-thread-number/131141/2 "2025-07-29T03:19:01Z")

</div>

You can use an outer for loop,

```julia-auto
Threads.@threads for it in 1:threads_to_use

```

and put inside it the divided tasks.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [July 29, 2025, 3:32am UTC](https://discourse.julialang.org/t/best-way-to-parallelize-for-loop-with-given-thread-number/131141/3 "2025-07-29T03:32:21Z")

</div>

Use OhMyThreads.jl

Which allows you to set these dynamically

```julia-auto
@set begin
            reducer=+
            ntasks=ntasks
        end

```
