Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I kill a ruby thread after a certain amount of time?

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
like image 836
John Bachir Avatar asked Oct 26 '11 01:10

John Bachir


2 Answers

Maybe the Timeout class is what you need.

def myfunc
  Thread.new{
    Timeout::timeout(20) {
      #do stuff
    }
  }

  # continue on asynchronously
end
like image 90
Miguel Avatar answered Sep 25 '22 00:09

Miguel


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.

like image 41
Adrian Shum Avatar answered Sep 27 '22 00:09

Adrian Shum