Ruby threads and variable

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

    The problem is that you have created 11 threads that are all trying to access the same variable i which was defined by the main thread of your program. One trick to avoid that is to call Thread.new inside a method; then the variable i that the thread has access to is just the particular i that was passed to the method, and it is not shared with other threads. This takes advantage of a closure.

    require 'thread'
    
    def run(i)
      puts i
    end
    
    def start_thread(i)
      Thread.new { run i }
    end
    
    for i in 0..10
      start_thread i
      sleep 0.1
    end
    

    Result:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    (I added the sleep just to guarantee that the threads run in numerical order so we can have tidy output, but you could take it out and still have a valid program where each thread gets the correct argument.)

提交回复
热议问题