Created
July 8, 2017 23:58
-
-
Save picatz/c3c7856aee3c7b912b623843fb4295ce to your computer and use it in GitHub Desktop.
Thread Pool'd threaded_scan Method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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