# Control number of threads

**URL:** <https://discourse.julialang.org/t/control-number-of-threads/62887>\
**Category:** New to Julia\
**Tags:** question, parallel\
**Created:** [June 14, 2021, 12:36pm UTC](https://discourse.julialang.org/t/control-number-of-threads/62887 "2021-06-14T12:36:54Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![oxinabox](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oxinabox/32/206603_2.png) [@oxinabox](https://discourse.julialang.org/u/oxinabox)\
**Post date:** [August 1, 2021, 5:43pm UTC](https://discourse.julialang.org/t/control-number-of-threads/62887/3 "2021-08-01T17:43:22Z")

</div>

## Semaphore

You can use what ever threading solution you want. (Including `Threads.@threads` )  
plus a [`Base.Semaphore`](https://docs.julialang.org/en/v1/base/parallel/#Base.Semaphore) to control number of threads active at a time.

> **[Semaphore (programming)](https://en.wikipedia.org/wiki/Semaphore_(programming))**
>
> In computer science, a semaphore is a variable or abstract data type used to control access to a common resource by multiple threads and avoid critical section problems in a concurrent system such as a multitasking operating system. Semaphores are a type of synchronization primitive. A trivial semaphore is a plain variable that is changed (for example, incremented or decremented, or toggled) depending on programmer-defined conditions.
> A useful way to think of a semaphore as used in a real-world ...

Something like

```julia
using Threads
sem = Base.Semaphore(2) # at most 2 at a time
Threads.@threads for ii in 1:100
    Base.acquire(sem)
    println(threadid())
    Base.release(sem)
end

```

This will ensure only 2 threads are doing anything at a time.  
THough which two may change (and in the case of `Threads.@thread` will because of how it allocates work in advance).

It may not lead to optimal scheduling however.

### [ThreadPools.jl](https://github.com/tro3/ThreadPools.jl/tree/d6da10bad2ffeceb9ced75c0e151b29b9b256dbe)

ThreadPools exposes multiple different scheduling algorithms and they can take a pool argument of a subset of threads which you can construct in advance

```julia
using ThreadPools
pool = ThreadPools.StaticPool(3, 2) # use only 2 threads, starting from thread 3
@tthreads pool for ii in 1:100
    println(threadid())
end

```

This actually will ensure only thread #3 and #4 are used.

---

_[View the full topic](https://discourse.julialang.org/t/control-number-of-threads/62887)._
