Skip to content

Instantly share code, notes, and snippets.

@roidrage
Created May 17, 2009 12:51
Show Gist options
  • Save roidrage/113002 to your computer and use it in GitHub Desktop.
Save roidrage/113002 to your computer and use it in GitHub Desktop.
require 'monitor'
class ConnectionPool
class Connection
end
def initialize
@mutex = Monitor.new
@condition = @mutex.new_cond
@pool = {}
end
def current_connection_id
Thread.current.object_id
end
def connection
@mutex.synchronize do
loop do
if @pool[current_connection_id]
return @pool[current_connection_id]
else
if @pool.size == 10
@condition.wait_while {@pool.size == 10}
else
@pool[current_connection_id] = Connection.new
return @pool[current_connection_id]
end
end
end
end
end
def check_in
@mutex.synchronize do
@pool.delete(current_connection_id)
@condition.signal
end
end
end
pool = ConnectionPool.new
threads = []
200.times do
threads << Thread.new do
pool.connection
i = 0
while i < 1000000
i+=1
end
pool.check_in
end
end
threads.each {|t| t.join}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment