Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Ruby (http://www.velocityreviews.com/forums/f66-ruby.html)
-   -   thread scheduling question (http://www.velocityreviews.com/forums/t847256-thread-scheduling-question.html)

Jeffrey Flint 01-09-2008 03:33 AM

thread scheduling question
 
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[i].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[i] << 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

--
Posted via http://www.ruby-forum.com/.



All times are GMT. The time now is 04:55 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.