Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ruby Threading (See related posts)

Uses Ruby (version 1.8) threading to run code in parallel which reduces the time taken for the script to complete.
require 'ping' #from core classes
@ip_prefix='192.168.1.'

def ping_ip(i)
  puts "Found #{@ip_prefix + i.to_s}" if Ping.pingecho(@ip_prefix+i.to_s,1)
end

p50 = Thread.new{(1..50).each{|i| ping_ip(i) };puts 'p50-finished'}
p100 = Thread.new{(51..100).each{|i| ping_ip(i) };puts 'p100-finished'}
p150 = Thread.new{(101..150).each{|i| ping_ip(i) }; puts 'p150-finished'}
p200 = Thread.new{(151..200).each{|i| ping_ip(i) }; puts 'p200-finished'}
p254 = Thread.new{(201..254).each{|i| ping_ip(i) }; puts 'p254-finished'}

output:
Found 192.168.1.2
Found 192.168.1.3
Found 192.168.1.8
Found 192.168.1.9
Found 192.168.1.10
Found 192.168.1.11
Found 192.168.1.12
Found 192.168.1.13
Found 192.168.1.15
Found 192.168.1.110
Found 192.168.1.21
Found 192.168.1.22
Found 192.168.1.140
p50-finished
p150-finished
Found 192.168.1.200
p200-finished
p100-finished
Found 192.168.1.254
p254-finished

This script took about 1 minute to complete, whereas the non-threaded script took around 4 minutes to complete.

Reference: Ruby Threads: RUBY THREADS [rubylearning.com]

*update 11:21pm*
I tried the same experiment again this time with 26 threads (9 pings each on average) and the script finished in under 15 seconds.

*update 11:39pm*
A separate thread for each ping seems to work best, since it only took a couple of seconds to finish.
(1..254).each{|i| Thread.new {puts 'Found ' + ip_prefix + i.to_s if Ping.pingecho(ip_prefix+i.to_s,10)}}


You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts