Ruby/Threads/Thread.new
Материал из Wiki.crossplatform.ru
Содержание |
Access the thread-local data from outside
thread = Thread.new do t = Thread.current t[:var1] = "This is a string" t[:var2] = 365 end x = thread[:var1] # "This is a string" y = thread[:var2] # 365 has_var2 = thread.key?("var2") # true has_var3 = thread.key?("var3") # false
Create threads in a while loop
n = 1 while n <= 3 Thread.new { puts n } n += 1 end
manipulate variables from the outer scope
x = 1 y = 2 thread3 = Thread.new do sleep(rand(0)) x = 3 end sleep(rand(0)) puts x
Pass value into a thread
n = 1 while n <= 3 # Get a private copy of the current value of n in x Thread.new(n) {|x| puts x } n += 1 end
True local variables (not accessible from outside)
thread = Thread.new do t = Thread.current t["var3"] = 25 t[:var4] = "foobar" var3 = 99 # True local variables (not accessible from outside) var4 = "zorch" end a = thread[:var3] # 25 b = thread["var4"] # "foobar"
Use upto to create 3 threads
1.upto(3) {|n| Thread.new { puts n }}