How to check the number of threads

Threads.nthreads()

Output:

8

For me, I have eight threads at my disposal for code execution.

How to check thread id

Threads.threadid()

Output:

1

Since we are on the master thread, Threads.threadid() will return 1.

@threads Macro

Below we create a with 10 elements in it, then use multi-threads to put thread id used to process the given for loop. To use multi-thread, we use Threads.@threads in front of a for loop to indicate the region that follows are multi-threaded region.

a = zeros(10)
Threads.@threads for i = 1:10
           a[i] = Threads.threadid()
       end

Output:

10-element Vector{Float64}:
 1.0
 1.0
 2.0
 2.0
 3.0
 4.0
 5.0
 6.0
 7.0
 8.0

Reference

https://docs.julialang.org/en/v1/manual/multi-threading/