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

后端 未结 2 661
旧时难觅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: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

提交回复
热议问题