Sha256: c3074e9fd3cd6102707530d3e7cf53eb3d7f7e7bd4b61332f5878c19bb055b89

Contents?: true

Size: 909 Bytes

Versions: 1

Compression:

Stored size: 909 Bytes

Contents

# = Pool
#
# Generalized object pool implementation.
#
# code: gmosx
#
# (c) 2004 Navel, all rights reserved.
# $Id: pool.rb 71 2004-10-18 10:50:22Z gmosx $

require "thread"
require "monitor"

module N

# = Pool
#
# Implemente 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 # module

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
nitro-0.1.2 lib/n/utils/pool.rb