Programación en Ruby/Implementación de co-rutinas

De Wikilibros, la colección de libros de texto de contenido libre.

El manejo de threads(Corrutinas) en ruby es muy sencillo, la creación de threads se basa en pasar un bloque a la creación de un objeto de la clase thread.

t1 = Thread.new do
 10.times do
  puts "hello from thread 1"
  sleep(0.2)
 end
end
t2 = Thread.new do 
 10.times do
  puts "hello from thread 2"
  sleep(0.2)
 end
end
t1.join
t2.join

Para pasar parámetros se hace de la siguiente forma:

t1 = Thread.new(1) do |id|
 10.times do
  puts "hello from thread #{id}"
  sleep(0.2)
 end
end
t2 = Thread.new(2) do |id|
 10.times do
  puts "hello from thread #{id}"
  sleep(0.2)
 end
end
t1.join
t2.join

Para controlar las secciones críticas tan solo hay que cambiar la variable de clase critical a true:

counter = 0;
t1 = Thread.new do
 100000.times do
  Thread.critical = true
  counter += 1
  Thread.critical = false 
 end
end
t2 = Thread.new do
 100000.times do
  Thread.critical = true
  counter -= 1
  Thread.critical = false
 end
end
t1.join
t2.join
puts counter