Class: ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/threadpool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(min, max = nil, &block) ⇒ ThreadPool

Returns a new instance of ThreadPool.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/threadpool.rb', line 16

def initialize (min, max = nil, &block)
	@min   = min
	@max   = max || min
	@block = block

	@cond  = ConditionVariable.new
	@mutex = Mutex.new

	@todo    = []
	@workers = []

	@spawned       = 0
	@waiting       = 0
	@shutdown      = false
	@trim_requests = 0
	@auto_trim     = false

	@mutex.synchronize {
		min.times {
			spawn_thread
		}
	}
end

Instance Attribute Details

#maxObject (readonly)

Returns the value of attribute max.



14
15
16
# File 'lib/threadpool.rb', line 14

def max
  @max
end

#minObject (readonly)

Returns the value of attribute min.



14
15
16
# File 'lib/threadpool.rb', line 14

def min
  @min
end

#spawnedObject (readonly)

Returns the value of attribute spawned.



14
15
16
# File 'lib/threadpool.rb', line 14

def spawned
  @spawned
end

Instance Method Details

#auto_trim!Object



41
# File 'lib/threadpool.rb', line 41

def auto_trim!;    @auto_trim = true;  end

#auto_trim?Boolean

Returns:

  • (Boolean)


40
# File 'lib/threadpool.rb', line 40

def auto_trim?;    @auto_trim;         end

#backlogObject



51
52
53
54
55
# File 'lib/threadpool.rb', line 51

def backlog
	@mutex.synchronize {
		@todo.length
	}
end

#no_auto_trim!Object



42
# File 'lib/threadpool.rb', line 42

def no_auto_trim!; @auto_trim = false; end

#process(*args, &block) ⇒ Object Also known as: <<



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/threadpool.rb', line 57

def process (*args, &block)
	unless block || @block
		raise ArgumentError, 'you must pass a block'
	end

	@mutex.synchronize {
		raise 'unable to add work while shutting down' if @shutdown

		@todo << [args, block]

		if @waiting == 0 && @spawned < @max
			spawn_thread
		end

		@cond.signal
	}
end

#resize(min, max = nil) ⇒ Object



44
45
46
47
48
49
# File 'lib/threadpool.rb', line 44

def resize (min, max = nil)
	@min = min
	@max = max || min

	trim!
end

#shutdownObject



90
91
92
93
94
95
96
97
# File 'lib/threadpool.rb', line 90

def shutdown
	@mutex.synchronize {
		@shutdown = true
		@cond.broadcast
	}

	@workers.first.join until @workers.empty?
end

#trim(force = false) ⇒ Object



77
78
79
80
81
82
83
84
# File 'lib/threadpool.rb', line 77

def trim (force = false)
	@mutex.synchronize {
		if (force || @waiting > 0) && @spawned - @trim_requests > @min
			@trim_requests -= 1
			@cond.signal
		end
	}
end

#trim!Object



86
87
88
# File 'lib/threadpool.rb', line 86

def trim!
	trim true
end