1

我正在尝试使用 IO.pipe 在进程之间发送消息,但是在等待完成消息时遇到了某种饥饿。

代码:https ://carc.in/#/r/12ly

4

1 回答 1

2

I see one w_waiter.puts and 2 times r_waiter.gets, that's why it blocks. If I add another w_waiter.puts after the first one, it finishes. Is that the problem?

EDIT: I also tried this in Ruby

r_producer, w_producer = IO.pipe
r_waiter, w_waiter = IO.pipe

2.times do |i|
  fork do
    puts "in fork #{i}"
    loop do
      message = r_producer.gets.chomp
      sleep 0.1
      puts "#{message} from #{i}"
      break if message == "0"
    end
    puts "sending finish"
    w_waiter.puts "finish"
  end
end

10.times do |i|
  w_producer.puts i + 1
end

2.times do
  w_producer.puts 0
end

2.times { r_waiter.gets }
puts "end of the program"

Same result.

I'm not sure using a same pipe for two forked processes work. You should create one pipe for each process.

Alternatively (I don't know what your program is), you could use spawn and channels, as described in the concurrency guide: http://crystal-lang.org/docs/guides/concurrency.html

于 2016-06-27T14:08:19.247 回答