Ruby Programming/Reference/Objects/Thread/Standard Library/Mutex

MutexEdit

The Mutex class (loadable via require 'thread') is a way of guaranteeing concurrency for a specific block.

Timing out a waitEdit

You can time out a wait like this in 1.9.2 (or jruby)

require 'thread'
a = Mutex.new
b = ConditionVariable.new
a.synchronize {
 a.wait(b, 3) # timeout after 3 secs
}

In 1.8 non jruby, you can use the timeout library, like

require 'thread'
require 'timeout'
a = Mutex.new
b = ConditionVariable.new

begin
Timeout::timeout(3) {
  a.synchronize {
    a.wait(b)
  }
}
rescue Timeout::Error
 # timed out
end

ReferencesEdit

a tutorial

Last modified on 9 June 2012, at 16:39