|
| 1 | +require 'concurrent/actor/utils/balancer' |
| 2 | + |
| 3 | +module Concurrent |
| 4 | + module Actor |
| 5 | + module Utils |
| 6 | + |
| 7 | + # Allows to create a pool of workers and distribute work between them |
| 8 | + # @param [Integer] size number of workers |
| 9 | + # @yield [balancer, index] a block spawning an worker instance. called +size+ times. |
| 10 | + # The worker should be descendant of AbstractWorker and supervised, see example. |
| 11 | + # @yieldparam [Balancer] balancer to pass to the worker |
| 12 | + # @yieldparam [Integer] index of the worker, usually used in its name |
| 13 | + # @yieldreturn [Reference] the reference of newly created worker |
| 14 | + # @example |
| 15 | + # class Worker < Concurrent::Actor::Utils::AbstractWorker |
| 16 | + # def work(message) |
| 17 | + # p message * 5 |
| 18 | + # end |
| 19 | + # end |
| 20 | + # |
| 21 | + # pool = Concurrent::Actor::Utils::Pool.spawn! 'pool', 5 do |balancer, index| |
| 22 | + # Worker.spawn name: "worker-#{index}", supervise: true, args: [balancer] |
| 23 | + # end |
| 24 | + # |
| 25 | + # pool << 'asd' << 2 |
| 26 | + # # prints: |
| 27 | + # # "asdasdasdasdasd" |
| 28 | + # # 10 |
| 29 | + class Pool < RestartingContext |
| 30 | + def initialize(size, &worker_initializer) |
| 31 | + @balancer = Balancer.spawn name: :balancer, supervise: true |
| 32 | + @workers = Array.new(size, &worker_initializer.curry[@balancer]) |
| 33 | + @workers.each { |w| Type! w, Reference } |
| 34 | + end |
| 35 | + |
| 36 | + def on_message(message) |
| 37 | + @balancer << message |
| 38 | + end |
| 39 | + end |
| 40 | + |
| 41 | + class AbstractWorker < RestartingContext |
| 42 | + def initialize(balancer) |
| 43 | + @balancer = balancer |
| 44 | + @balancer << :subscribe |
| 45 | + end |
| 46 | + |
| 47 | + def on_message(message) |
| 48 | + work message |
| 49 | + ensure |
| 50 | + @balancer << :subscribe |
| 51 | + end |
| 52 | + |
| 53 | + def work(message) |
| 54 | + raise NotImplementedError |
| 55 | + end |
| 56 | + end |
| 57 | + end |
| 58 | + end |
| 59 | +end |
0 commit comments