Skip to content

Instantly share code, notes, and snippets.

@mikeys
Last active May 25, 2016 22:09
Show Gist options
  • Save mikeys/c491231997edf0da415fb166c8645c8d to your computer and use it in GitHub Desktop.
Save mikeys/c491231997edf0da415fb166c8645c8d to your computer and use it in GitHub Desktop.
require 'thread'
require 'monitor'
class ThreadPool
class Thread
attr_reader :thread
def initialize(pool)
@thread = ::Thread.new do
@active = true
while active?
if @action
@action.call
@action = nil
pool.release(self)
end
::Thread.stop
end
end
end
def active?
@active
end
def stop!
@active = false
@thread.run
end
def run(&block)
@action = block
@thread.run
end
end
include MonitorMixin
def initialize(pool_size, *args)
super(*args)
@stack = Array.new(pool_size) { Thread.new(self) }
@all_threads = @stack.dup
@empty_cond = new_cond
end
def run_async
t = borrow
t.run { yield }
end
def shutdown!
@all_threads.each(&:stop!)
end
private
def borrow
synchronize do
@empty_cond.wait_while { @stack.empty? }
@stack.pop
end
end
def release(thread)
synchronize do
@stack.push(thread)
@empty_cond.signal
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment