Skip to content

Instantly share code, notes, and snippets.

@picatz
Created July 8, 2017 23:58
Show Gist options
  • Save picatz/c3c7856aee3c7b912b623843fb4295ce to your computer and use it in GitHub Desktop.
Save picatz/c3c7856aee3c7b912b623843fb4295ce to your computer and use it in GitHub Desktop.
Thread Pool'd threaded_scan Method
# previous code...
class PortScanner
# previous code ...
def threaded_scan(threads: 10)
pool = Queue.new
# Spool up jobs in a queue with its own thread.
Thread.new do
@ports.each do |port|
connect_to port do |job|
pool << job
end
end
# Spool up one EndOfOp per Thread
threads.times do
pool << EndOfOp.new
end
end
# Spool through those jobs.
threads.times do
Thread.new do
while job = pool.pop
break if job.instance_of? EndOfOp
job.call
end
end
end
# Wait for the threads to finnish spool'n through the queue.
Thread.list.each{ |t| t.join unless t == Thread.current }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment