|
| 1 | +require 'concurrent' # => false |
| 2 | + |
| 3 | +# logger = Logger.new(STDOUT) |
| 4 | +# Concurrent.configuration.logger = logger.method(:add) |
| 5 | + |
| 6 | +# First option is to use operation pool |
| 7 | + |
| 8 | +class ActorDoingIO < Concurrent::Actor::RestartingContext |
| 9 | + def on_message(message) |
| 10 | + # do IO operation |
| 11 | + end |
| 12 | + |
| 13 | + def default_executor |
| 14 | + Concurrent.configuration.global_operation_pool |
| 15 | + end |
| 16 | +end |
| 17 | + |
| 18 | +actor_doing_io = ActorDoingIO.spawn :actor_doing_io |
| 19 | + # => #<Concurrent::Actor::Reference:0x7fb6fc906068 /actor_doing_io (ActorDoingIO)> |
| 20 | +actor_doing_io.executor == Concurrent.configuration.global_operation_pool |
| 21 | + # => true |
| 22 | + |
| 23 | +# It can be also built into a pool so there is not too many IO operations |
| 24 | + |
| 25 | +class IOWorker < Concurrent::Actor::Utils::AbstractWorker |
| 26 | + def work(io_job) |
| 27 | + # do IO work |
| 28 | + sleep 0.1 |
| 29 | + puts "#{path} second:#{(Time.now.to_f*100).floor} message:#{io_job}" |
| 30 | + end |
| 31 | + |
| 32 | + def default_executor |
| 33 | + Concurrent.configuration.global_operation_pool |
| 34 | + end |
| 35 | +end |
| 36 | + |
| 37 | +pool = Concurrent::Actor::Utils::Pool.spawn('pool', 2) do |balancer, index| |
| 38 | + IOWorker.spawn(name: "worker-#{index}", args: [balancer]) |
| 39 | +end |
| 40 | + # => #<Concurrent::Actor::Reference:0x7fb6fc964190 /pool (Concurrent::Actor::Utils::Pool)> |
| 41 | + |
| 42 | +pool << 1 << 2 << 3 << 4 << 5 << 6 |
| 43 | + # => #<Concurrent::Actor::Reference:0x7fb6fc964190 /pool (Concurrent::Actor::Utils::Pool)> |
| 44 | + |
| 45 | +# prints two lines each second |
| 46 | +# /pool/worker-0 second:1414677666 message:1 |
| 47 | +# /pool/worker-1 second:1414677666 message:2 |
| 48 | +# /pool/worker-0 second:1414677667 message:3 |
| 49 | +# /pool/worker-1 second:1414677667 message:4 |
| 50 | +# /pool/worker-0 second:1414677668 message:5 |
| 51 | +# /pool/worker-1 second:1414677668 message:6 |
| 52 | + |
| 53 | +sleep 1 # => 1 |
0 commit comments