Skip to content

Commit 336666b

Browse files
Be more robust when setting threadid of task
This uses the same function Dagger uses to set the thread id of a task, it's a bit more robust than the simple ccall. Co-authored-by: Julian P Samaroo <[email protected]>
1 parent 64423b2 commit 336666b

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

src/internals.jl

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,40 @@ end
2727
Base.schedule(t::StableTask) = (schedule(t.t); t)
2828
Base.schedule(t, val; error=false) = (schedule(t.t, val; error); t)
2929

30+
"""
31+
set_task_tid!(task::Task, tid::Integer)
32+
33+
Sets the thread ID of `task` to `tid`. Retries up to 10 times in case
34+
the ccall fails.
35+
36+
Calls `jl_set_task_tid` internally.
37+
38+
## Extended help
39+
40+
Copied from [Dagger.jl](https://github.com/JuliaParallel/Dagger.jl/blob/62f8307a46436bfed1f12414b812a776147a6851/src/utils/tasks.jl#L1),
41+
credit to Julian Samaroo for the implementation and for letting us know about this!
42+
"""
43+
function set_task_tid!(task::Task, tid::Integer)
44+
task.sticky = true
45+
ctr = 0
46+
while true
47+
ret = ccall(:jl_set_task_tid, Cint, (Any, Cint), task, tid-1)
48+
if ret == 1
49+
break
50+
elseif ret == 0
51+
yield()
52+
else
53+
error("Unexpected retcode from jl_set_task_tid: $ret")
54+
end
55+
ctr += 1
56+
if ctr > 10
57+
@warn "Setting task TID to $tid failed, giving up!"
58+
return
59+
end
60+
end
61+
@assert Threads.threadid(task) == tid "jl_set_task_tid failed!"
62+
end
63+
3064
"""
3165
@spawn [:default|:interactive] expr
3266
@@ -107,7 +141,7 @@ macro spawnat(thrdid, ex)
107141
thunk_wrap = () -> (ret[] = thunk(); nothing)
108142
local task = Task(thunk_wrap)
109143
task.sticky = true
110-
ccall(:jl_set_task_tid, Cvoid, (Any, Cint), task, $tid - 1)
144+
set_task_tid!(task, $tid)
111145
if $(Expr(:islocal, var))
112146
put!($var, task)
113147
end

0 commit comments

Comments
 (0)