Rubyでスレッド

スレッドの生成

ary = ('a'..'c').to_a
threads = Array.new

ary.each do |elem|
	threads << Thread.new(elem) do |s|
		sleep(rand(0.1))
		3.times{|i| print "#{s} : #{i}\n" }
	end
end

threads.each{|thread| thread.join}

実行結果

D:\workplace>ruby test.r
a : 0
a : 1
a : 2
b : 0
b : 1
b : 2
c : 0
c : 1
c : 2

D:\workplace>ruby test.r
a : 0
a : 1
a : 2
c : 0
c : 1
c : 2
b : 0
b : 1
b : 2

D:\workplace>ruby test.r
c : 0
c : 1
c : 2
b : 0
b : 1
b : 2
a : 0
a : 1
a : 2

D:\workplace>ruby test.r
b : 0
b : 1
b : 2
a : 0
a : 1
a : 2
c : 0
c : 1
c : 2