Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Add Comment
Please, Sign In to add comment