Class: Thimble::ThimbleQueue
- Inherits:
-
Object
- Object
- Thimble::ThimbleQueue
- Defined in:
- lib/ThimbleQueue.rb
Direct Known Subclasses
Instance Attribute Summary collapse
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
- #close(now = false) ⇒ Object
- #closed? ⇒ Boolean
-
#initialize(size, name) ⇒ ThimbleQueue
constructor
A new instance of ThimbleQueue.
-
#push(x) ⇒ Object
This will push whatever it is handed to the queue.
-
#push_flat(x) ⇒ Object
This will flatten any nested arrays out and feed them one at a time to the queue.
- #take ⇒ Object
- #to_a ⇒ Object
Constructor Details
#initialize(size, name) ⇒ ThimbleQueue
Returns a new instance of ThimbleQueue.
7 8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/ThimbleQueue.rb', line 7 def initialize(size, name) raise ArgumentError.new("make sure there is a size for the queue greater than 1! size received #{size}") unless size >= 1 @id = Digest::SHA256.digest(rand(10**100).to_s + Time.now.to_i.to_s) @name = name @size = size @mutex = Mutex.new @queue = [] @closed = false @close_now = false @empty = ConditionVariable.new @full = ConditionVariable.new end |
Instance Attribute Details
#size ⇒ Object (readonly)
Returns the value of attribute size.
6 7 8 |
# File 'lib/ThimbleQueue.rb', line 6 def size @size end |
Instance Method Details
#close(now = false) ⇒ Object
60 61 62 63 64 65 66 67 |
# File 'lib/ThimbleQueue.rb', line 60 def close(now = false) @mutex.synchronize do @closed = true @close_now = true if now @full.broadcast @empty.broadcast end end |
#closed? ⇒ Boolean
77 78 79 |
# File 'lib/ThimbleQueue.rb', line 77 def closed? @close end |
#push(x) ⇒ Object
This will push whatever it is handed to the queue
36 37 38 39 40 41 42 43 |
# File 'lib/ThimbleQueue.rb', line 36 def push(x) @mutex.synchronize do while !offer(x) @full.wait(@mutex) end @empty.broadcast end end |
#push_flat(x) ⇒ Object
This will flatten any nested arrays out and feed them one at a time to the queue.
47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/ThimbleQueue.rb', line 47 def push_flat(x) if x.respond_to? :each x.each {|item| push(item)} else @mutex.synchronize do while !offer(x) @full.wait(@mutex) end @empty.broadcast end end end |
#take ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/ThimbleQueue.rb', line 20 def take @mutex.synchronize do while !@close_now a = @queue.shift if !a.nil? @full.broadcast return a else return nil if @closed @empty.wait(@mutex) end end end end |
#to_a ⇒ Object
69 70 71 72 73 74 75 |
# File 'lib/ThimbleQueue.rb', line 69 def to_a a = [] while item = take a << item.item end a end |