Sha256: b752ce2742a00aa0d68f59b04fea06f80004d7e9ee801fd4e9522783e42c33d2

Contents?: true

Size: 1.49 KB

Versions: 4

Compression:

Stored size: 1.49 KB

Contents

# Copyright: Copyright (c) 2004  Nicolas Despres. All rights reserved.
# Author: Nicolas Despres  <polrop@lrde.epita.fr>.
# License: Gnu General Public License.

# $LastChangedBy: ertai $
# $Id: timeout_ex.rb 186 2005-04-03 00:07:45Z ertai $


require 'thread'


module TimeoutEx

  class Error < Interrupt; end

  module_function
  def timeout(sec, exception=Error, mutex=nil, &block)
    if sec > 0
      thread = Thread.new(mutex) do |mutex|
        Thread.current[:timeout_mutex] = mutex
        block[]
      end
      sleep(sec)
      if thread.alive?
        unless mutex.nil?
          mutex.synchronize { thread.kill if thread.alive? }
        else
          thread.kill
        end
        raise(exception, 'execution expired')
      end
    else
      block[]
    end
    true
  end

end # module TimeoutEx


if defined? TEST_MODE or __FILE__ == $0


require 'test/unit/ui/yaml/testrunner'


class TimeoutExTest < Test::Unit::TestCase

  def test_timeout
    run = false
    assert_raises(TimeoutEx::Error) do
      TimeoutEx.timeout(0.1) do
        sleep(0.5)
        run = true
      end
    end
    assert(! run)
  end

  def test_mutex
    run = false
    assert_raises(TimeoutEx::Error) do
      TimeoutEx.timeout(0.1, TimeoutEx::Error, Mutex.new) do
        Thread.current[:timeout_mutex].synchronize do
          sleep(0.5)
          run = true
        end
      end
    end
    assert(run)
  end

  def test_no_timeout
    assert(TimeoutEx.timeout(0.1) { nil })
  end

end # class TimeoutExTest


end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
ttk-0.1.576 ruby_ex/timeout_ex.rb
ttk-0.1.580 ruby_ex/timeout_ex.rb
ttk-0.1.579 ruby_ex/timeout_ex.rb
vcs-0.2.148 ruby_ex/timeout_ex.rb