multithreading - Threads in Ruby -
why code work (i see output 1 2 3):
for in 1..3 thread.new{ puts } end
however, following code not produce same output (i not see output 1 2 3)?
for in 1..3 thread.new{ sleep(5) puts } end
when hit end of script, ruby exits. if add sleep 10
after final loop, can see output show up. (albeit, 3 each time, because binding i
reflects value @ end of processing, , sleep causes thread switch loop.)
you might want like:
threads = [] in 1..3 threads << thread.new { sleep 5 puts } end threads.map {|t| t.join }
that wait threads terminate before exiting.
Comments
Post a Comment