Sha256: 9b74dfb144c7cf5fe549e42ff5a8b78dca1b2a91aeac081a26d155ff6c747d77

Contents?: true

Size: 905 Bytes

Versions: 3

Compression:

Stored size: 905 Bytes

Contents

# * George Moschovitis  <gm@navel.gr>
# (c) 2004-2005 Navel, all rights reserved.
# $Id: pool.rb 282 2005-03-10 12:24:53Z gmosx $

require 'thread'
require 'monitor'

module N

# Generalized object pool implementation. Implemented as a thread 
# safe stack. Exclusive locking is needed both for push and pop. 
#
# INVESTIGATE: Could use the SizedQueue/Queue.

class Pool < Array
	include MonitorMixin
	
	def initialize
		super
		@cv = new_cond()
	end

	# Add, restore an object to the pool.
	
	def push(obj)
		synchronize do
			super
			@cv.signal()
		end
	end
	
	# Obtain an object from the pool.
	
	def pop
		synchronize do
			@cv.wait_while { empty? }
			super
		end
	end

	# Obtains an object, passes it to a block for processing
	# and restores it to the pool.

	def obtain
		result = nil
		
		begin
			obj = pop()

			result = yield(obj)
		ensure
			push(obj)
		end

		return result
	end
	
end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
glue-0.13.0 lib/glue/pool.rb
glue-0.15.0 lib/glue/pool.rb
glue-0.14.0 lib/glue/pool.rb