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

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Mutex[edit | edit source]

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

Timing out a wait[edit | edit source]

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

References[edit | edit source]

a tutorial