M
Mike Houghton
Hello,
I'm new (very new!) to Ruby but not to programming. I have a
Thread/class inheritance question.I'm trying to make a simple timer
class that extends Thread and repeats a block <count> times and each
repetition separated by <period> seconds. Here's the code
--------------
class Timer < Thread
def initialize( period, count, &action )
puts "Begin initialize"
super
@period = period
@count = count
@action = action
puts "End initialize"
end # initialize
def start
puts "Begin start"
1.upto(@count) do
sleep(@period)
@action.call
end
puts "End start"
end # start
end #class Timer
threads = []
threads << Timer.new(0.77,3){puts "hi"}
threads.each{ |thr| thr.start}
-------
The output is
Begin initialize
hi
End initialize
Begin start
hi
hi
hi
End start
-------
In my ignorance I expected the supplied block not to be executed in
initialize
and to be executed only in the start method. Please would someone
explain where
I'm going wrong and how to correct it.
Many Thanks
Mike
I'm new (very new!) to Ruby but not to programming. I have a
Thread/class inheritance question.I'm trying to make a simple timer
class that extends Thread and repeats a block <count> times and each
repetition separated by <period> seconds. Here's the code
--------------
class Timer < Thread
def initialize( period, count, &action )
puts "Begin initialize"
super
@period = period
@count = count
@action = action
puts "End initialize"
end # initialize
def start
puts "Begin start"
1.upto(@count) do
sleep(@period)
@action.call
end
puts "End start"
end # start
end #class Timer
threads = []
threads << Timer.new(0.77,3){puts "hi"}
threads.each{ |thr| thr.start}
-------
The output is
Begin initialize
hi
End initialize
Begin start
hi
hi
hi
End start
-------
In my ignorance I expected the supplied block not to be executed in
initialize
and to be executed only in the start method. Please would someone
explain where
I'm going wrong and how to correct it.
Many Thanks
Mike