Last active
January 7, 2016 07:04
-
-
Save nowherekai/407c71d42d9421025a6f to your computer and use it in GitHub Desktop.
This file contains 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
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