How to kill thread?

killing is never safe, I didn’t suggest otherwise. A safe way would be a task handling its own channel, like the following:

struct Stop end
struct Continue end

function safe_hanging(ch::Channel)
    println("I'm hanging on thread ", threadid())
    signal = Continue()
    while true
        isready(ch) && (signal = take!(ch))
        signal == Stop() && break
        sleep(1)
    end
    println("stopped!")
end

julia> mytask = Ref{Task}();

julia> ch = Channel(safe_hanging, taskref=mytask, spawn=true)
I'm hanging on thread 2
Channel{Any}(sz_max:0,sz_curr:0)

julia> mytask[]
Task (runnable) @0x000000011001f850

julia> put!(ch, Stop());
stopped!

julia> mytask[]
Task (done) @0x000000011001f850

Also a task with its own try catch error handling could be a safe way.

8 Likes