# How to kill thread?

**URL:** <https://discourse.julialang.org/t/how-to-kill-thread/34236>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [February 6, 2020, 5:25am UTC](https://discourse.julialang.org/t/how-to-kill-thread/34236 "2020-02-06T05:25:10Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![pbayer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pbayer/32/11675_2.png) [@pbayer](https://discourse.julialang.org/u/pbayer)\
**Post date:** [February 6, 2020, 8:08am UTC](https://discourse.julialang.org/t/how-to-kill-thread/34236/8 "2020-02-06T08:08:44Z")

</div>

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

```julia
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.

---

_[View the full topic](https://discourse.julialang.org/t/how-to-kill-thread/34236)._
