Created
May 17, 2009 12:51
-
-
Save roidrage/113002 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 '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