Reputation: 94
I'm trying to use IO.pipe to send messages between processes, but I run into some kind of starvation when I'm waiting for finish messages.
Code: https://carc.in/#/r/12ly
Upvotes: 1
Views: 127
Reputation: 2926
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
Upvotes: 2