I want a thread that I create to die if it doesn't finish after a certain amount of time. Is there any elegant and/or idiomatic way to do this? Right now I am thinking to make a watcher thread:
def myfunc
t = Thread.new{
#do stuff
}
# watcher thread
Thread.new{
result = t.join(20) # join returns nil if it timed out
t.kill if result.nil?
}
# continue on asynchronously from both threads
end
Maybe the Timeout class is what you need.
def myfunc
Thread.new{
Timeout::timeout(20) {
#do stuff
}
}
# continue on asynchronously
end
I believe in most situation, you should control the "life" of thread by the program logic in the thread.
Assume the thread is actually a infinite loop, instead of having a plain while(true), you may have an instance variable (e.g. is_running) and make the loop being something like while(is_running). If other thread wanna stop this thread, they can simply (directly or indirectly) make is_running false. The working thread then can finish off the last piece of work on hand and finish the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With