When do you need to pass arguments to `Thread.new`?

后端 未结 2 666
旧时难觅i
旧时难觅i 2021-02-12 20:25

Local variables defined outside of a thread seem to be visible from inside so that the following two uses of Thread.new seem to be the same:

a = :fo         


        
相关标签:
2条回答
  • 2021-02-12 20:44

    When you pass a variable into a thread like that, then the thread makes a local copy of the variable and uses it, so modifications to it do not affect the variable outside of the thread you passed in

    a = "foo"
    Thread.new{ a = "new"}
    p a # => "new"
    Thread.new(a){|d| d = "old"} 
    p a # => "new"
    p d # => undefined
    
    0 讨论(0)
  • 2021-02-12 20:58

    I think I hit the actual problem. With a code like this:

        sock = Socket.unix_server_socket(SOCK)
        sock.listen 10
        while conn = sock.accept do
            io, address = conn
            STDERR.puts "#{io.fileno}: Accepted connection from '#{address}'"
            Thread.new{ serve io }
        end
    

    it appears to work when accepting few connections. The problem comes when accepting connections quickly one after another. The update to local variable io will be reflected in multiple concurrent threads unless passed as argument to Thread.new

    0 讨论(0)
提交回复
热议问题