Skip to content

Instantly share code, notes, and snippets.

@rosenfeld
Created June 7, 2016 12:49
Show Gist options
  • Save rosenfeld/6dd627bf821ca9a520ea2fea0f0695b9 to your computer and use it in GitHub Desktop.
Save rosenfeld/6dd627bf821ca9a520ea2fea0f0695b9 to your computer and use it in GitHub Desktop.

Revisions

  1. rosenfeld created this gist Jun 7, 2016.
    33 changes: 33 additions & 0 deletions thread-pool.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    require 'thread' # for Mutex: Ruby doesn't provide out of the box thread-safe arrays

    class ThreadPool
    def initialize(max_threads = 10)
    @pool = SizedQueue.new(max_threads)
    max_threads.times{ @pool << 1 }
    @mutex = Mutex.new
    @running_threads = []
    end

    def run(&block)
    @pool.pop
    @mutex.synchronize do
    @running_threads << Thread.start do
    begin
    block[]
    rescue Exception => e
    puts "Exception: #{e.message}\n#{e.backtrace}"
    ensure
    @pool << 1
    end
    end
    end
    end

    def await_completion
    @running_threads.each &:join
    end
    end

    pool = ThreadPool.new 5
    10.times {|i| pool.run{sleep 1} }
    pool.await_completion