# Stop threads after a certain condition is true

**URL:** https://discourse.julialang.org/t/stop-threads-after-a-certain-condition-is-true/111062
**Category:** New to Julia
**Tags:** question
**Created:** [March 2, 2024, 3:41pm UTC](https://discourse.julialang.org/t/stop-threads-after-a-certain-condition-is-true/111062 "2024-03-02T15:41:22Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![nickk2002](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nickk2002/32/202480_2.png) [@nickk2002](https://discourse.julialang.org/u/nickk2002)
#### Post date: [March 2, 2024, 3:48pm UTC](https://discourse.julialang.org/t/stop-threads-after-a-certain-condition-is-true/111062/2 "2024-03-02T15:48:39Z")

</div>

Looking here: [How to kill thread?](https://discourse.julialang.org/t/how-to-kill-thread/34236)  
I think this could maybe work, but is ugly.

```julia
using .Threads

function hanging()
    while true
        println("I'm hanging on thread:", threadid())
        sleep(1)
    end
end

function wrapper_run()
    try
        hang = Threads.@spawn hanging();
        sleep(4)
        schedule(hang, ErrorException("stop"), error=true)
    catch e 
        println("Good")
    end 
    println("hello")
end

wrapper_run()

```

This will stop the thread after 4 seconds but not crash

---

_[View the full topic](https://discourse.julialang.org/t/stop-threads-after-a-certain-condition-is-true/111062)._
