Ruby中的线程范围

时间:2011-07-12 13:22:57

标签: ruby multithreading scope

有一种方法可以将变量范围扩展到线程而不必传递所有内容,给定一个具有以下方法的类:

  def initialize
    @server = TCPServer.new('localhost',456)
  end

  def start
    threads = []
    while (upload = @server.accept)
      threads << Thread.new(upload) do |connection|
         some_method_here(connection)
      end
    end
    threads.each {|t| t.join }
  end

  def some_method_here(connection)
     variable = "abc"
     another_method(connection,variable)
  end

  def another_method(connection,variable)
      puts variable.inspect
      connection.close
  end

3 个答案:

答案 0 :(得分:6)

如果我说得对,你想使用线程局部变量(参见ruby rdoc for Thread#[])

来自rdoc:

   a = Thread.new { Thread.current["name"] = "A"; Thread.stop }
   b = Thread.new { Thread.current[:name]  = "B"; Thread.stop }
   c = Thread.new { Thread.current["name"] = "C"; Thread.stop }
   Thread.list.each {|x| puts "#{x.inspect}: #{x[:name]}" }

produces:

   #<Thread:0x401b3b3c sleep>: C
   #<Thread:0x401b3bc8 sleep>: B
   #<Thread:0x401b3c68 sleep>: A
   #<Thread:0x401bdf4c run>:

所以你的例子会用

Thread.current[:variable] = "abc"
Thread.current[:variable] # => "abc"

之前只使用variable的地方

答案 1 :(得分:1)

Thread.current[:variable_name] = ...

答案 2 :(得分:0)

您可以在ApplicationController中尝试around_filter

around_filter :apply_scope 
  def apply_scope 
  Document.where(:user_id => current_user.id).scoping do 
  yield 
end