Class: Concurrent::Channel

Inherits:
Actor
  • Object
show all
Includes:
Stoppable
Defined in:
lib/concurrent/channel.rb

Overview

Channel is a functional programming variation of Actor, based very loosely on the MailboxProcessor agent in F#. Actor is used to create objects that receive messages from other threads then processes those messages based on the behavior of the class. Channel creates objects that receive messages and processe them using the block given at construction. Channel is implemented as a subclass of Actor and supports all message-passing methods of that class. Channel also supports pools with a shared mailbox.

Examples:

Basic usage

channel = Concurrent::Channel.new do |msg|
  sleep(1)
  puts "#{msg}\n"
end

channel.run! => #<Thread:0x007fa123d95fc8 sleep>

channel.post("Hello, World!") => 1
# wait...
=> Hello, World!

future = channel.post? "Don't Panic." => #<Concurrent::IVar:0x007fa123d6d9d8 @state=:pending...
future.pending? => true
# wait...
=> "Don't Panic."
future.fulfilled? => true

channel.stop => true  

See Also:

Constant Summary

Constants included from Runnable

Runnable::LifecycleError

Instance Method Summary collapse

Methods included from Stoppable

#before_stop

Methods inherited from Actor

pool

Methods included from Runnable

included, #run, #run!, #running?, #stop

Methods included from Postable

#<<, #forward, #post, #post!, #post?, #ready?

Constructor Details

#initialize {|message| ... } ⇒ Channel

Initialize a new object with a block operation to be performed in response to every received message.

Yields:

  • (message)

    Removes the next message from the queue and processes it

Yield Parameters:

  • msg (Array)

    The next message post to the channel

Raises:

  • (ArgumentError)


44
45
46
47
48
# File 'lib/concurrent/channel.rb', line 44

def initialize(&block)
  raise ArgumentError.new('no block given') unless block_given?
  super()
  @task = block
end