Skip to content

Instantly share code, notes, and snippets.

@nowherekai
Last active January 7, 2016 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nowherekai/407c71d42d9421025a6f to your computer and use it in GitHub Desktop.
Save nowherekai/407c71d42d9421025a6f to your computer and use it in GitHub Desktop.
require 'redis'
class Connpool
DEFAULTS = { size: 5 }
def initialize(options = {}, &block)
raise ArgumentError, 'Conn pool requires a block' unless block
options = DEFAULTS.merge(options)
@size = options.fetch(:size)
@available = Queue.new
@size.times do
@available.push block.call
end
@connection = nil
end
def with
@connection = @available.pop
yield conn
ensure
@available.push @connection
end
end
$pool = Connpool.new(size: 2) { Redis.new }
t1 = Thread.new do
$pool.with do |conn|
sleep 20
conn.set("name", "joy")
end
end
t2 = Thread.new do
$pool.with do |conn|
sleep 20
conn.set("age", "20")
end
end
sleep 2
puts "after sleep"
$pool.with do |conn|
puts "should block here"
conn.set("hello", "word")
end
t1.join
t2.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment