Skip to content

Commit 0f9a54d

Browse files
add way to get index of thread in its threadpool
1 parent 12698af commit 0f9a54d

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

base/threadingconstructs.jl

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,19 @@ julia> Threads.threadid(Threads.@spawn "foo")
3535
"""
3636
threadid() = Int(ccall(:jl_threadid, Int16, ())+1)
3737

38+
"""
39+
Threads.threadpool_threadidx() -> Int
40+
41+
Return the index of the current thread in its threadpool.
42+
i.e. For the first default thread when 1 interactive thread exists this returns 1
43+
because the interactive threadpool comes first in threadid order.
44+
"""
45+
function threadpool_threadidx()
46+
pool = threadpool()
47+
first_tid = _threadpool_first_threadid(pool)
48+
return Int(threadid() - first_tid + 1)
49+
end
50+
3851
# lower bound on the largest threadid()
3952
"""
4053
Threads.maxthreadid() -> Int
@@ -144,17 +157,29 @@ function threadpoolsize(pool::Symbol = :default)
144157
return _nthreads_in_pool(tpid)
145158
end
146159

160+
function _threadpool_first_threadid(pool::Symbol)
161+
if pool === :interactive
162+
return 1
163+
end
164+
if pool === :default
165+
ni = _nthreads_in_pool(Int8(0))
166+
return ni+1
167+
else
168+
error("invalid threadpool specified")
169+
end
170+
end
171+
147172
"""
148173
threadpooltids(pool::Symbol)
149174
150175
Returns a vector of IDs of threads in the given pool.
151176
"""
152177
function threadpooltids(pool::Symbol)
153-
ni = _nthreads_in_pool(Int8(0))
178+
first_tid = _threadpool_first_threadid(pool)
154179
if pool === :interactive
155-
return collect(1:ni)
180+
return collect(1:_nthreads_in_pool(Int8(0)))
156181
elseif pool === :default
157-
return collect(ni+1:ni+_nthreads_in_pool(Int8(1)))
182+
return collect(first_tid:first_tid+_nthreads_in_pool(Int8(1)))
158183
else
159184
error("invalid threadpool specified")
160185
end

0 commit comments

Comments
 (0)