title: Ruby multithreaded ping loses packets only if there is more than one thread
body: <p>I wrote a ruby script to ping multiple hosts in parallel and print pairs of [host : result]. This is the script I produced so far:</p>
  
  <pre><code>require 'thread'
  
      out = ""
      queue = Queue.new
      hosts = ["www.google.com", "www.onet.pl", "www.lego.com", "www.example.com"]
  
      hosts.each do |x|
        queue &lt;&lt; x;
      end
  
      hash = Hash.new "NO REPLY"
      threads = []
      NO_OF_THREADS = 4;
  
      for i in 1..NO_OF_THREADS
        threads &lt;&lt; Thread.new do
  
          until queue.empty? do
            host = queue.pop(true) rescue nil
  
            if host
              out = `ping #{host} -c 10 | grep 'packet loss'`
              hash[host] = out
            end
  
          end # until
        end # thread
      end # for
  
      threads.each do |t|
          t.join
      end
  
      puts hash
  </code></pre>
  
  <p>When I set the number of threads to <code>1</code>, I get <code>0% packets lost</code> responses, but when I try to execute multiple threads at once I get a lot of lost packets. I executed this script with a long list of hosts to check and many threads; the result was that most hosts from my list lost 100% of the packets.</p>
  
  <p>I tried synchronization with a <code>Mutex</code> instead of using a <code>Queue</code> and adding a <code>sleep</code> within the thread, but I didn't help. At this point I'm not sure if there is an issue with my code or I misunderstood how ping is supposed to work. Why am I having a lot of packets lost? Is there a way to fix it?</p>