本文简要介绍ruby语言中 Ractor.select
的用法。
用法
select(*ractors, [yield_value:, move: false]) → [ractor or symbol, obj]
等待第一个 ractor 在其传出端口中有内容,从该 ractor 读取,并返回该 ractor 和接收到的对象。
r1 = Ractor.new {Ractor.yield 'from 1'}
r2 = Ractor.new {Ractor.yield 'from 2'}
r, obj = Ractor.select(r1, r2)
puts "received #{obj.inspect} from #{r.inspect}"
# Prints: received "from 1" from #<Ractor:#2 test.rb:1 running>
如果给定的 ractor 之一是当前的 ractor,并且它将被选中,则 r
将包含 :receive
符号而不是 ractor 对象。
r1 = Ractor.new(Ractor.current) do |main|
main.send 'to main'
Ractor.yield 'from 1'
end
r2 = Ractor.new do
Ractor.yield 'from 2'
end
r, obj = Ractor.select(r1, r2, Ractor.current)
puts "received #{obj.inspect} from #{r.inspect}"
# Prints: received "to main" from :receive
如果提供了 yield_value
,则如果另一个 Ractor
正在调用 take
,则可能会产生该值。在这种情况下,将返回 [:yield, nil]
对:
r1 = Ractor.new(Ractor.current) do |main|
puts "Received from main: #{main.take}"
end
puts "Trying to select"
r, obj = Ractor.select(r1, Ractor.current, yield_value: 123)
wait
puts "Received #{obj.inspect} from #{r.inspect}"
这将打印:
Trying to select Received from main: 123 Received nil from :yield
move
布尔标志定义是否应复制(默认)或移动产生的值。
相关用法
- Ruby Ractor.send用法及代码示例
- Ruby Ractor.shareable?用法及代码示例
- Ruby Ractor.receive_if用法及代码示例
- Ruby Ractor.close_incoming用法及代码示例
- Ruby Ractor.count用法及代码示例
- Ruby Ractor.current用法及代码示例
- Ruby Ractor.new用法及代码示例
- Ruby Ractor.receive用法及代码示例
- Ruby Ractor.close_outgoing用法及代码示例
- Ruby Ractor.yield用法及代码示例
- Ruby Ractor.take用法及代码示例
- Ruby Ractor.make_shareable用法及代码示例
- Ruby Ractor类用法及代码示例
- Ruby Racc模块用法及代码示例
- Ruby Range.end用法及代码示例
- Ruby Range new()用法及代码示例
- Ruby Rational.inspect用法及代码示例
- Ruby Random.bytes用法及代码示例
- Ruby Random hex()用法及代码示例
- Ruby Range.size用法及代码示例
- Ruby Rational.rational <=>用法及代码示例
- Ruby Rational to_i()用法及代码示例
- Ruby Rational.rat ** numeric用法及代码示例
- Ruby Random random_number()用法及代码示例
- Ruby Range last()用法及代码示例
注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Ractor.select。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。