thread scheduling question

J

Jeffrey Flint

This code sends a message around a ring of queues. When each queue
pops, it prints out its message.

The code seems to work, but it seems to hang on the io, which I don't
understand. I would expect the messages to print very quickly. The
messages only print inside of irb when I depress the carriage return
repeatedly.

Thank you!

Jeff


=================================
require 'thread'

class Ring
attr_writer :size, :mbox, :agents
attr_reader :size, :mbox, :agents

def initialize (size)
@size = size
@mbox = []
@agents = []
(1..size).each do
@mbox << Queue.new
end

(0..size-1).each do |index|
@agents << Thread.new(index) do |i|
loop do
msg = @mbox.pop
case msg
when "start"
@mbox[(i+1)%size] << 1 if i == 0

when "halt"
break

else
print("#{i}: #{msg}: #{Thread.current} #{Time.now}\n")
STDOUT.flush
(@mbox[(i+1)%size] << msg + 1) if i!=0
Thread.pass
end
end
end
end
end

def rpc(i, msg)
@mbox << msg
end

def start ()
rpc(0,"start")
end

def halt ()
@mbox.each { |m| m << "halt" }
@agents.each {|thr| thr.join }
end

end

R = Ring.new(10)
R.start

Attachments:
http://www.ruby-forum.com/attachment/1266/ring.rb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top