Hi, in Rubytalk 55895 [
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/55895 ] Matz
wrote that generators can be written with Threads as well as with
Callcc. He then gave an example with Calcc. Works fine. Here is my
example with Threads. But I’m not sure whether it is good programming.
Is it free of race conditions, for example? Thanks.
module Math
def Math.divisible(number)
square_root = Math.sqrt(number).floor
for divisor in 2…square_root
return true if number % divisor==0
end
return false
end
end
class PrimeGenerator
def initialize
@thread = Thread.new { # create a separate thread
loop do # this thread is an infinite loop…
Thread.stop # going to sleep, goodnight everybody
# Uh oh ... Brrr. Where am I?
# I have been woken up and scheduled to run.
# See (*)
Thread.critical = true # take exclusive right to run
# this right is necessary, because I must be kept awake
# by scheduler until next prime is computed
complex_computation # do something interesting..
Thread.critical = false # release exclusive right
end
}
@number = 1
end
def next
@thread.run
return @number
end
def complex_computation
@number += 1
@number += 1 while Math.divisible(@number)
end
end
p = PrimeGenerator.new
puts p.next #> 2
puts p.next #> 3
puts p.next #> 5
puts p.next #> 7