new
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.
thr.join
The calling thread
will suspend execution and run thr
.
thr
exits or until limit
seconds have passed
if we have used thr.join(limit)
.
limit
expires, nil
will be returned, otherwise thr
is returned.
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...
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" endNecesitamos 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