Class: Minx::Channel
- Inherits:
-
Object
- Object
- Minx::Channel
- Defined in:
- lib/minx/channel.rb
Overview
A Channel is used to transmit messages between processes in a synchronized manner.
Instance Method Summary collapse
-
#each {|message| ... } ⇒ Object
Enumerate over the messages sent to the channel.
-
#initialize ⇒ Channel
constructor
A new instance of Channel.
-
#readable? ⇒ Boolean
Returns whether there are any processes waiting to write.
-
#receive(options = {}) ⇒ Object
Read a message off the channel.
-
#send(message) ⇒ nil
(also: #<<)
Write a message to the channel.
Constructor Details
#initialize ⇒ Channel
Returns a new instance of Channel.
6 7 8 9 |
# File 'lib/minx/channel.rb', line 6 def initialize @readers = [] @writers = [] end |
Instance Method Details
#each {|message| ... } ⇒ Object
Enumerate over the messages sent to the channel.
63 64 65 |
# File 'lib/minx/channel.rb', line 63 def each yield receive while true end |
#readable? ⇒ Boolean
Returns whether there are any processes waiting to write.
70 71 72 |
# File 'lib/minx/channel.rb', line 70 def readable? return !@writers.empty? end |
#receive(options = {}) ⇒ Object
Read a message off the channel.
If no messages have been written to the channel, the calling process will block, only resuming when a write occurs. This behavior can be suppressed by calling receive
with :async => true
, in which case the call will return immediately; the next time the calling process yields, it may be resumed with a message from the channel.
46 47 48 49 50 51 52 53 |
# File 'lib/minx/channel.rb', line 46 def receive( = {}) if @writers.empty? @readers << Fiber.current Minx.yield unless [:async] else @writers.shift.resume end end |
#send(message) ⇒ nil Also known as: <<
Write a message to the channel.
If no readers are waiting, the calling process will block until one comes along.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/minx/channel.rb', line 18 def send() if @readers.empty? @writers << Fiber.current # Yield control Minx.yield # Yield a message back to a reader. Minx.yield() else @readers.shift.resume() end return nil end |