From: Daniel Berger Date: 2009-08-13T18:14:49+09:00 Subject: Re: How to make net-ping thread safe? Laurent Julliard wrote: > Hi, > > I'm using the excellent net-ping gem (v 1.2.2 on Ruby 1.8.6 Linux box) > from Daniel Berger to ping a number of machines on a local area network. > > I recently refactored my code to use threads and I'm having troubles > with Net::Ping::ICMP. I'm trying to ping several machines, each one in a > separate thread and I'm seing strange things like when one machine is on > all three machines are reported on (although two are off). When I run my > program with one thread only the on/off state shows as expected. > > So I'm wondering if the Net::Ping::ICMP#ping method is thread safe? > Daniel said he made no attempt to make sure that the code is and > usggested that I post this question here. > > The code for the method Net::Ping::ICMP#ping is here: > http://www.koders.com/ruby/fidE6256BC790B8AD197544CE26287B5C7D3200E4C8.aspx?s=icmp#L5 > > > (line 61) > > Here is also a simplified version of my own code: > > ----------------------------------------------- > > require 'rubygems' > require 'net/ping/icmp' > > WORK_STATIONS = ['192.168.1.1', '192.168.1.2', '192.168.1.3'] > threads = [] > ping_objects = [] > > WORK_STATIONS.each do |ip| > ping_objects << Net::Ping::ICMP.new(ip) > threads << Thread.new(ip, ping_objects.last) do |ip, p| > puts "Monitoring #{ip}..." > loop do > puts "#{ip} is #{p.ping ? 'on' : 'off'}" > sleep 2 > end > end > end > > threads.each { |th| th.join } Very late reply here. Odd. When I ran nearly identical code it worked as expected. However, when applied Joel's patch it didn't work right - it reported all hosts as off. Not sure why. That was on OS X 10.4.9 with Ruby 1.8.6-368 btw. Regards, Dan