gpt4 book ai didi

ruby - Ruby 中的线程作用域

转载 作者:太空宇宙 更新时间:2023-11-03 17:18:17 24 4
gpt4 key购买 nike

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

  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

最佳答案

如果我没看错你想使用线程局部变量(参见 ruby rdoc 的 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

关于ruby - Ruby 中的线程作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6664846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com