File: messaging.out.rb

package info (click to toggle)
ruby-concurrent 1.1.6%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 30,284 kB
  • sloc: ruby: 30,875; java: 6,117; ansic: 288; makefile: 9; sh: 6
file content (36 lines) | stat: -rw-r--r-- 1,345 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
require 'algebrick'                                # => true

# Actor message protocol definition with Algebrick
Protocol = Algebrick.type do
  variants Add      = type { fields! a: Numeric, b: Numeric },
           Subtract = type { fields! a: Numeric, b: Numeric }
end                                                # => Protocol(Add | Subtract)

class Calculator < Concurrent::Actor::RestartingContext
  include Algebrick::Matching

  def on_message(message)
    # pattern matching on the message with deconstruction
    # ~ marks values which are passed to the block
    match message,
          (on Add.(~any, ~any) do |a, b|
            a + b
          end),
          # or using multi-assignment
          (on ~Subtract do |(a, b)|
            a - b
          end)
  end
end 

calculator = Calculator.spawn('calculator')
    # => #<Concurrent::Actor::Reference:0x7fbedba52d90 /calculator (Calculator)>
addition = calculator.ask Add[1, 2]
    # => <#Concurrent::Promises::Future:0x7fbedc05f7b0 pending>
subtraction = calculator.ask Subtract[1, 0.5]
    # => <#Concurrent::Promises::Future:0x7fbedd891388 pending>
results = (addition & subtraction)
    # => <#Concurrent::Promises::Future:0x7fbedc04eeb0 pending>
results.value!                                     # => [3, 0.5]

calculator.ask! :terminate!                        # => true