当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Ractor.select用法及代码示例


本文简要介绍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-lang.org大神的英文原创作品 Ractor.select。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。