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


Ruby Ractor.receive用法及代碼示例

本文簡要介紹ruby語言中 Ractor.receive 的用法。

用法

receive → msg
也別名為:recv

從當前 Ractor 的傳入端口隊列接收傳入消息,該消息由 send 發送到那裏。

r = Ractor.new do
  v1 = Ractor.receive
  puts "Received: #{v1}"
end
r.send('message1')
r.take
# Here will be printed: "Received: message1"

或者,可以使用私有實例方法receive

r = Ractor.new do
  v1 = receive
  puts "Received: #{v1}"
end
r.send('message1')
r.take
# Here will be printed: "Received: message1"

如果隊列為空,該方法將阻塞。

r = Ractor.new do
  puts "Before first receive"
  v1 = Ractor.receive
  puts "Received: #{v1}"
  v2 = Ractor.receive
  puts "Received: #{v2}"
end
wait
puts "Still not received"
r.send('message1')
wait
puts "Still received only one"
r.send('message2')
r.take

輸出:

Before first receive
Still not received
Received: message1
Still received only one
Received: message2

如果在 ractor 上調用了 close_incoming ,則如果傳入隊列中沒有更多消息,該方法將引發 Ractor::ClosedError

Ractor.new do
  close_incoming
  receive
end
wait
# in `receive': The incoming port is already closed => #<Ractor:#2 test.rb:1 running> (Ractor::ClosedError)

相關用法


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