How to kill Thread which is running in background in julia

I have one project in that project there is process which executing some calculations . and while execution is running when user request to stop the execution of process then Django send request to julia in julia that process is assign to one thread which is running in background and i want to kill or terminate that thread ,so please help me to how to kill thread which is running in background

julia> task = Threads.@spawn sleep(100)
Task (runnable) @0x00007fcc8fa3c650

julia> Base.throwto(task, InterruptException())
ERROR: InterruptException:
Stacktrace:
 [1] try_yieldto(undo::typeof(identity))
   @ Base ./task.jl:931
 [2] throwto(t::Task, exc::Any)
   @ Base ./task.jl:943
 [3] top-level scope
   @ REPL[16]:1

julia> istaskfailed(task)
true

Given that Base.throwto is undocumented, I don’t think this is really a good, trustworthy solution though. It was the only one I could find.

4 Likes

I usually use schedule(...; error=true) for that:

julia> task = Threads.@spawn sleep(100);

julia> task
Task (runnable) @0x00007f660297c650

julia> schedule(task, :stop, error=true)
Task (failed) @0x00007f660297c650
:stop
Stacktrace:
 [1] try_yieldto(undo::typeof(Base.ensure_rescheduled))
   @ Base ./task.jl:920
 [2] wait()
   @ Base ./task.jl:984
 [3] wait(c::Base.GenericCondition{Base.Threads.SpinLock}; first::Bool)
   @ Base ./condition.jl:130
 [...]

julia> istaskfailed(task)
true
1 Like

The best practice would be to introduce a stop condition into the running background process loop, and then satisfy that condition on interrupt.