Control number of threads

Semaphore

You can use what ever threading solution you want. (Including Threads.@threads )
plus a Base.Semaphore to control number of threads active at a time.

Something like

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

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

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.

5 Likes