Threads Ruby
Simple script en ruby, que muestra el manejo de threads(hilos)
El programa debe calcular el area de circulos y triangulos por separado.Mayor informacion Ruby Multithreading
class Triangle
attr_accessor :attributes
def initialize
@attributes = {
base: Random.rand(1..10),
high: Random.rand(10..15)
}
end
end
class Circle
attr_accessor :attributes
def initialize
@attributes = {
radio: Random.rand(1..10)
}
end
end
class QAreas
@triangles = []
@circles = []
def self.generate_triangles
10.times do |id|
t = Triangle.new
@triangles << [id, t.attributes[:base], t.attributes[:high] ]
end
end
def self.triangle_area(b,h)
return (b * h ) / 2
end
def self.generate_circles
10.times do |id|
c = Circle.new
@circles << [id,c.attributes[:radio]]
end
end
def self.circle_area r
return Math::PI * (r*r)
end
def self.start
QAreas::generate_triangles
QAreas::generate_circles
print 'Type-id Area'
puts ''
th_triangle = Thread.new do
@triangles.each do |id, base, high|
area = QAreas::triangle_area(base,high)
print 'T -', id, ' - ', base, '-', high, '-',area
puts ''
sleep(0.2)
end
end
th_cirlce = Thread.new do
@circles.each do |id, r|
area = QAreas::circle_area r
print 'C -', id, ' - ', r
puts ''
sleep(0.2)
end
end
th_triangle.join
th_cirlce.join
end
end
QAreas.start
No hay comentarios:
Publicar un comentario