Class: Concurrent::Selectable::Channel
- Defined in:
- lib/concurrent/selectable/channel.rb
Overview
A thread-safe FIFO channel of Ruby objects which can be selected on as if it were an IO object.
Instance Method Summary collapse
-
#empty? ⇒ Boolean
Returns true if the channel is currently empty (additional external synchronization is normally required if other threads can manipulate the channel).
-
#get(blocking = true, default_value = nil) ⇒ Object
Attempts to get a value from the channel and returns it, blocking if none is available and
blocking
is true. -
#initialize ⇒ Channel
constructor
A new instance of Channel.
-
#put(value) ⇒ Object
(also: #<<)
Places
value
on the channel.
Methods inherited from Base
Constructor Details
#initialize ⇒ Channel
Returns a new instance of Channel.
44 45 46 47 48 |
# File 'lib/concurrent/selectable/channel.rb', line 44 def initialize super() @lock = ::Mutex.new @channel = ::Queue.new end |
Instance Method Details
#empty? ⇒ Boolean
Returns true if the channel is currently empty (additional external synchronization is normally required if other threads can manipulate the channel)
80 81 82 |
# File 'lib/concurrent/selectable/channel.rb', line 80 def empty? @channel.empty? end |
#get(blocking = true, default_value = nil) ⇒ Object
Attempts to get a value from the channel and returns it, blocking if none is available and blocking
is true. If blocking
is false, then default_value
is returned if no value is currently available.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/concurrent/selectable/channel.rb', line 53 def get(blocking=true, default_value=nil) loop do @lock.synchronize do size = @channel.size if size.nonzero? value = @channel.deq internal_reset if size == 1 # i.e. if we removed the last remaining return value end end return default_value unless blocking wait end end |
#put(value) ⇒ Object Also known as: <<
Places value
on the channel.
69 70 71 72 73 74 |
# File 'lib/concurrent/selectable/channel.rb', line 69 def put(value) @lock.synchronize do internal_set if @channel.empty? @channel.enq value end end |