Ruby threads and variable

前端 未结 3 964
抹茶落季
抹茶落季 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

    The block that is passed to Thread.new may actually begin at some point in the future, and by that time the value of i may have changed. In your case, they all have incremented up to 10 prior to when all the threads actually run.

    To fix this, use the form of Thread.new that accepts a parameter, in addition to the block:

    require 'thread'
    
    def run(i)
      puts i
    end
    
    while true
      for i in 0..10
        Thread.new(i) { |j| run(j) }
      end
      sleep(100)
    end
    

    This sets the block variable j to the value of i at the time new was called.

提交回复
热议问题