跳轉到內容

Ruby 程式設計/參考/物件/執行緒/標準庫/互斥鎖

來自華夏公益教科書,自由的教科書

互斥鎖

[編輯 | 編輯原始碼]

Mutex 類(可透過 require 'thread' 載入)是一種確保特定塊併發性的方法。

等待超時

[編輯 | 編輯原始碼]

您可以在 1.9.2(或 jruby)中像這樣超時等待

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

在 1.8 非 jruby 中,您可以使用 timeout 庫,例如

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

教程

華夏公益教科書