Class: ThreadStore
- Inherits:
-
Object
- Object
- ThreadStore
- Defined in:
- lib/thread_store.rb
Overview
Class ThreadStore
Instance Attribute Summary collapse
-
#cycles ⇒ Object
readonly
Returns the value of attribute cycles.
-
#max ⇒ Object
readonly
Returns the value of attribute max.
Instance Method Summary collapse
-
#add(thread) ⇒ Object
Add a new thread to the ThreadStore.
-
#initialize(max = 100) ⇒ ThreadStore
constructor
Create a new ThreadStore.
-
#inspect ⇒ Object
:nodoc:.
-
#keep(n = nil) ⇒ Object
Keep only the number passed of threads.
-
#kill! ⇒ Object
Kill all threads.
-
#size ⇒ Object
How long is our ThreadStore.
Constructor Details
#initialize(max = 100) ⇒ ThreadStore
Create a new ThreadStore.
- max
-
max number of threads to store (when exhausted, older threads will
just be killed and discarded). Default is 100. If 0 or negative no threads will be discarded until #keep is called.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/thread_store.rb', line 10 def initialize(max = 100) @store = [] @max = max > 0 ? max : 0 @cycles = 0 @killer_thread = Thread.new do loop do sleep 2 while @store.empty? sleep 1 @store.each_with_index do |thread, i| th = @store.delete_at(i) if thread.nil? or ! thread.alive? th = nil end @cycles += 1 end end end |
Instance Attribute Details
#cycles ⇒ Object (readonly)
Returns the value of attribute cycles.
3 4 5 |
# File 'lib/thread_store.rb', line 3 def cycles @cycles end |
#max ⇒ Object (readonly)
Returns the value of attribute max.
3 4 5 |
# File 'lib/thread_store.rb', line 3 def max @max end |
Instance Method Details
#add(thread) ⇒ Object
Add a new thread to the ThreadStore
32 33 34 35 36 37 |
# File 'lib/thread_store.rb', line 32 def add(thread) if thread.instance_of?(Thread) and thread.respond_to?(:alive?) @store << thread keep(@max) if @max > 0 end end |
#inspect ⇒ Object
:nodoc:
27 28 29 |
# File 'lib/thread_store.rb', line 27 def inspect # :nodoc: sprintf("#<%s:0x%x @max=%d, @size=%d @cycles=%d>", self.class.name, __id__, @max, size, @cycles) end |
#keep(n = nil) ⇒ Object
Keep only the number passed of threads
- n
-
number of threads to keep (default to @max if @max > 0)
42 43 44 45 46 47 48 |
# File 'lib/thread_store.rb', line 42 def keep(n = nil) if n.nil? raise StandardError, "You need to pass the number of threads to keep!" if @max == 0 n = @max end @store.shift.kill while @store.length > n end |
#kill! ⇒ Object
Kill all threads
51 52 53 |
# File 'lib/thread_store.rb', line 51 def kill! @store.shift.kill while @store.length > 0 end |
#size ⇒ Object
How long is our ThreadStore
56 |
# File 'lib/thread_store.rb', line 56 def size; @store.length; end |