Created
January 8, 2018 19:22
-
-
Save AaronM04/98676c7169d2b7e75cfea84248e740c2 to your computer and use it in GitHub Desktop.
Simple Ruby thread pool
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
class ThreadPool | |
def initialize(num_threads) | |
@tasks = Queue.new # contains either blocks to run, or :terminate | |
@threads = [] | |
@terminated = false # only used to stop new work from being enqueued | |
num_threads.times do | |
@threads << Thread.new{ process }.run | |
end | |
end | |
def run(&block) | |
raise "cannot add new work while awaiting completion" if @terminated | |
@tasks << block | |
end | |
def await_completion | |
@terminated = true | |
@threads.count.times do | |
@tasks << :terminate | |
end | |
@threads.each do |thread| | |
thread.join | |
end | |
end | |
private | |
def process | |
# worker thread run loop | |
while true | |
item = @tasks.pop # will block if nothing in task queue | |
break if item == :terminate | |
item[] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment