How to deal with threadid() <= nthreads() being not true in 1.12?

Hello,

I recently found out that this assertion fires on 1.12.0-rc1 (seems fine on 1.11.6):

using Base.Threads
@threads for i in 1:100
    @assert threadid() <= nthreads()
end

Some of my code has @threads :static and assumes threadid() <= nthreads() for accessing “thread-local” buffers.

What are the options for adapting my code to the new behaviour? Should I use nthreads(:interactive) + nthreads(:default) as the upper bound?

PS. I read PSA: Thread-local state is no longer recommended. I have still been using @threads :static because it’s simple.

PS. Originally discovered in moving tests for rational functions to the subfolder · SciML/StructuralIdentifiability.jl@ebfeeab · GitHub

Using :static is fine, assuming specific values for threadid is where the issue lies.

In particular, with thread adoption the number of OS threads may change over the course of execution. Don’t use threadid as an index.