Class: Minx::Channel

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

Overview

A Channel is used to transmit messages between processes in a synchronized manner.

Instance Method Summary collapse

Constructor Details

#initializeChannel

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.

Examples:

Iterating over channel messages

chan.each do |message|
  puts "Got #{message}!"
end

Yields:

  • (message)


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.

Returns:

  • (Boolean)

    true if you can receive a message from the channel



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.

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :async (Boolean) — default: false

    whether or not to block

Returns:

  • a message



46
47
48
49
50
51
52
53
# File 'lib/minx/channel.rb', line 46

def receive(options = {})
  if @writers.empty?
    @readers << Fiber.current
    Minx.yield unless options[: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.

Parameters:

  • message

    the message to be transmitted

Returns:

  • (nil)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/minx/channel.rb', line 18

def send(message)
  if @readers.empty?
    @writers << Fiber.current

    # Yield control
    Minx.yield

    # Yield a message back to a reader.
    Minx.yield(message)
  else
    @readers.shift.resume(message)
  end

  return nil
end