Method: Olib.timeout

Defined in:
lib/Olib/core/utils.rb

.timeout(sec) ⇒ Object

:yield: sec



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/Olib/core/utils.rb', line 88

def Olib.timeout(sec)   #:yield: +sec+
  return yield(sec) if sec == nil or sec.zero?

  begin
    current_thread = Thread.current
    x = Thread.start{ 
      begin
        yield(sec)
      rescue => e 
        current_thread.raise e
      end
    }
    y = Thread.start {
      begin
        sleep sec
      rescue => e
        x.raise e
      else
        x.kill
        current_thread.raise Olib::Errors::TimedOut
      end
    }
    x.value
  ensure
    if y
      y.kill
      y.join # make sure y is dead.
    end
  end
  
end