从其他方法访问ruby本地线程变量

时间:2016-05-10 15:44:03

标签: ruby multithreading

class Tour
  def destinations
    threads = []
    [:new_york, :london, :syndey].each { |city|
      @threads << Thread.new {
        where = city
        goto(where)
      }
    }
    threads.each(&:join)
  end

  def where=(location)
    Thread.current[:city] = location
  end

  def where
    Thread.current[:city]
  end

  def goto(city)
    puts "I am going to visit #{city}."
  end
end

Tour.new.destinations

为了在方法goto()中访问线程局部变量,线程局部变量必须像goto(where)一样传递给它,如果有许多其他类似的方法需要根据当前线程局部变量做事情:city,那么它也必须传递给其他方法。

我猜有一种优雅/红宝石方式可以避免将线程局部变量作为选项传递,这看起来像什么?

1 个答案:

答案 0 :(得分:4)

这似乎让你自己绊倒了很多。为每个线程初始化一个新对象可能更好。

class Tour
  def self.destinations
    threads = []

    [:new_york, :london, :sydney].each do |city|
      threads << Thread.new { Destination.new(city).go }
    end

    threads.each(&:join)
  end
end

class Destination
  attr_reader :location

  def initialize(location)
    @location = location
  end

  def go
    puts "I am going to visit #{location}."
  end
end

# Tour.destinations

建议阅读:https://blog.engineyard.com/2011/a-modern-guide-to-threads