| 
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 | # File 'lib/rubygems/core_ext/tcpsocket_init.rb', line 15
def initialize(host, serv, *rest)
  mutex = Thread::Mutex.new
  addrs = []
  threads = []
  cond_var = Thread::ConditionVariable.new
  Addrinfo.foreach(host, serv, nil, :STREAM) do |addr|
    Thread.report_on_exception = false
    threads << Thread.new(addr) do
            sleep IPV4_DELAY_SECONDS if addr.ipv4?
            Socket.tcp(addr.ip_address, serv, connect_timeout: CONNECTION_TIMEOUT).close
      mutex.synchronize do
        addrs << addr.ip_address
        cond_var.signal
      end
    end
  end
  mutex.synchronize do
    timeout_time = CONNECTION_TIMEOUT + Time.now.to_f
    while addrs.empty? && (remaining_time = timeout_time - Time.now.to_f) > 0
      cond_var.wait(mutex, remaining_time)
    end
    host = addrs.shift unless addrs.empty?
  end
  threads.each {|t| t.kill.join if t.alive? }
  super(host, serv, *rest)
end |