Skip to content

Commit 30f0612

Browse files
committed
Make setup_onfixedthread robust against errors
1 parent 992d48a commit 30f0612

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/C/context.jl

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,15 @@ function setup_onfixedthread()
4040
worker_task = Task() do
4141
while true
4242
f = take!(channel_input)
43-
put!(channel_output, f())
43+
ret = try
44+
Some(invokelatest(f))
45+
# invokelatest is necessary for development and interactive use.
46+
# Otherwise, only a method f defined in a world prior to the call of
47+
# launch_worker would work.
48+
catch e
49+
e, catch_backtrace()
50+
end
51+
put!(channel_output, ret)
4452
end
4553
end
4654
# code adapted from set_task_tid! in StableTasks.jl, itself taken from Dagger.jl
@@ -63,7 +71,17 @@ function setup_onfixedthread()
6371
end
6472
function onfixedthread(f)
6573
put!(channel_input, f)
66-
take!(channel_output)
74+
ret = take!(channel_output)
75+
if ret isa Tuple
76+
e, backtrace = ret
77+
printstyled(stderr, "ERROR: "; color=:red, bold=true)
78+
showerror(stderr, e)
79+
Base.show_backtrace(stderr, backtrace)
80+
println(stderr)
81+
throw(e) # the stacktrace of the actual error is printed above
82+
else
83+
something(ret)
84+
end
6785
end
6886
launch_worker, onfixedthread
6987
end

test/Core.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -836,3 +836,13 @@ end
836836
prop_task = fetch(task)
837837
@test properties == prop_task
838838
end
839+
840+
@testitem "on_main_thread" begin
841+
task = Threads.@spawn PythonCall.C.on_main_thread() do; Threads.threadid(); end
842+
@test fetch(task) == 1
843+
@test_throws DivideError redirect_stderr(devnull) do
844+
PythonCall.C.on_main_thread() do
845+
throw(DivideError())
846+
end
847+
end
848+
end

0 commit comments

Comments
 (0)