Ruby中的线程范围

Orb*_*bit 1 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
Run Code Online (Sandbox Code Playgroud)

pau*_*kul 6

如果我找到了你想要使用线程局部变量(参见线程#[] 的ruby rdoc)

来自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>:
Run Code Online (Sandbox Code Playgroud)

所以你的例子会用

Thread.current[:variable] = "abc"
Thread.current[:variable] # => "abc"
Run Code Online (Sandbox Code Playgroud)

无论你variable以前在哪里使用过