PSA: Thread-local state is no longer recommended; Common misconceptions about threadid() and nthreads()

I think this is perfectly fine, because you are not using the function threadid(). You can (should) call that ichunk to avoid confusion and there will be no concurrency issues there.

(You there have just used a simple way to divide the workload in chunks).

Note that you can use the same pattern using different variable names, an neither the task IDs or the number of chunks need to be the same as the number of threads:

n_threads = Threads.nthreads()
N = 100
nchunks = 20
out_chunks = [0.0 for _ in 1:nchunks]

Threads.@threads for ichunk in 1:nchunks
    for i in ichunk:nchunks:N
        # Do something with i to get x, not involving thread_id
        out_chunks[ichunk] += x
    end
end

This is what ChunkSplitters.jl does when using the :scatter chunk strategy. In fact, increasing the number of chunks can improve load balancing.

Ps. Your question is somehow ambiguous, because the answer to the introduction is yes, there’s a problem, but not with the actual code snippet you posted.

4 Likes