當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby Fiber.new用法及代碼示例

本文簡要介紹ruby語言中 Fiber.new 的用法。

用法

new(blocking: false) { |*args| ... } → fiber

創建新的 Fiber 。最初,光纖沒有運行,可以使用 resume 恢複。第一個 resume 調用的參數將傳遞給塊:

f = Fiber.new do |initial|
   current = initial
   loop do
     puts "current: #{current.inspect}"
     current = Fiber.yield
   end
end
f.resume(100)     # prints: current: 100
f.resume(1, 2, 3) # prints: current: [1, 2, 3]
f.resume          # prints: current: nil
# ... and so on ...

如果 blocking: false 被傳遞給 Fiber.newand 當前線程定義了 Fiber.scheduler ,則 Fiber 變為非阻塞(參見類文檔中的“非阻塞光纖”部分)。

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Fiber.new。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。