Creación de Threads

new

  1. Ruby makes it easy to write multi-threaded programs with the Thread class
  2. To start a new thread, just associate a block with a call to Thread.new
  3. A new thread will be created to execute the code in the block,
  4. the original thread will return from Thread.new immediately and resume execution with the next statement

arr = []
a, b, c = 1, 2, 3
Thread.new(a,b,c) { |d,e,f| arr << d << e << f }.join
arr #=> [1, 2, 3]
A ThreadError exception is raised if ::new is called without a block.

join

  1. When a thread calls thr.join The calling thread will suspend execution and run thr.
  2. The calling thread does not return until thr exits or until limit seconds have passed if we have used thr.join(limit).
  3. If the time limit expires, nil will be returned, otherwise thr is returned.
  4. Any threads not joined will be killed when the main program exits.
  5. If thr had previously raised an exception and the exception has not yet been processed, it will be processed at this time.
[~/ruby/threads(master)]$ cat join_with_timer.rb 
require 'thread'

y = Thread.new { 4.times { sleep 0.2; puts 'tick... ' }}
puts "Waiting" until y.join(0.1)

[~/ruby/threads(master)]$ ruby join_with_timer.rb 
Waiting
tick... 
Waiting
Waiting
tick... 
Waiting
Waiting
tick... 
Waiting
Waiting
tick...

Localidad y Privacidad

A thread can normally access any variables that are in scope when the thread is created.

Variables local to the block containing the thread code are local to the thread and are not shared.

Class Thread features a special facility that allows thread-local variables to be created and accessed by name.

You simply treat the thread object as if it were a Hash, writing to elements using []= and reading them back using [].

Veamos un ejemplo:

[~/ruby/threads(master)]$ cat sharing.rb 
require 'thread'
require 'barrier'

numthreads = 4
lastthread = numthreads-1
th = []
b = Barrier.new(numthreads)
(0..lastthread).each do |i|
  th[i] = Thread.new(i) do
    b.wait
    th[(i+1)%numthreads][:my_x] = i 
  end
end
th.each do |t| 
  t.join 
  print t[:my_x].to_s+"\n" 
end
Necesitamos la barrera proveida por Barrier para asegurarnos de que todas las threads han sido creadas en el momento en el que que cada thread escribe en la variable my_x de la thread siguiente.

La ejecución resulta en:

[~/ruby/threads(master)]$ ruby sharing.rb 
3
0
1
2



Subsecciones
Casiano Rodriguez León 2015-01-07