Ruby threads and variable

前端 未结 3 945
抹茶落季
抹茶落季 2021-01-05 15:58

Why the result is not from 1 to 10, but 10s only?

require \'thread\'

def run(i)
  puts i
end

while true
  for i in 0..10
    Thread.new{ run(i)}
  end
  sl         


        
3条回答
  •  囚心锁ツ
    2021-01-05 16:39

    @DavidGrayson is right.

    You can see here a side effect in for loop. In your case i variable scope is whole your file. While you are expecting only a block in your for loop as a scope. Actually this is wrong approach in idiomatic Ruby. Ruby gives you iterators for this job.

    (1..10).each do |i|
       Thread.new{ run(i)}
    end
    

    In this case scope of variable i will be isolated in block scope what means for each iteration you will get new local (for this block) variable i.

提交回复
热议问题