Class: Concurrent::Agent
- Inherits:
-
Object
- Object
- Concurrent::Agent
- Includes:
- Dereferenceable, UsesGlobalThreadPool, Observable
- Defined in:
- lib/concurrent/agent.rb
Overview
An agent is a single atomic value that represents an identity. The current value of the agent can be requested at any time (#deref). Each agent has a work queue and operates on the global thread pool. Consumers can #post code blocks to the agent. The code block (function) will receive the current value of the agent as its sole parameter. The return value of the block will become the new value of the agent. Agents support two error handling modes: fail and continue. A good example of an agent is a shared incrementing counter, such as the score in a video game.
Defined Under Namespace
Classes: Rescuer
Constant Summary collapse
- TIMEOUT =
5
Instance Attribute Summary collapse
-
#initial ⇒ Object
readonly
Returns the value of attribute initial.
-
#timeout ⇒ Object
readonly
Returns the value of attribute timeout.
Instance Method Summary collapse
- #<<(block) ⇒ Object
-
#initialize(initial, opts = {}) ⇒ Agent
constructor
A new instance of Agent.
- #post(&block) ⇒ Object
- #rescue(clazz = nil, &block) ⇒ Object (also: #catch, #on_error)
- #validate(&block) ⇒ Object (also: #validates, #validate_with, #validates_with)
Methods included from UsesGlobalThreadPool
Methods included from Dereferenceable
Constructor Details
#initialize(initial, opts = {}) ⇒ Agent
Returns a new instance of Agent.
26 27 28 29 30 31 32 |
# File 'lib/concurrent/agent.rb', line 26 def initialize(initial, opts = {}) @value = initial @rescuers = [] @validator = nil @timeout = opts[:timeout] || TIMEOUT (opts) end |
Instance Attribute Details
#initial ⇒ Object (readonly)
Returns the value of attribute initial.
23 24 25 |
# File 'lib/concurrent/agent.rb', line 23 def initial @initial end |
#timeout ⇒ Object (readonly)
Returns the value of attribute timeout.
24 25 26 |
# File 'lib/concurrent/agent.rb', line 24 def timeout @timeout end |
Instance Method Details
#<<(block) ⇒ Object
57 58 59 60 |
# File 'lib/concurrent/agent.rb', line 57 def <<(block) self.post(&block) return self end |
#post(&block) ⇒ Object
53 54 55 |
# File 'lib/concurrent/agent.rb', line 53 def post(&block) Agent.thread_pool.post{ work(&block) } unless block.nil? end |
#rescue(clazz = nil, &block) ⇒ Object Also known as: catch, on_error
34 35 36 37 38 39 40 41 |
# File 'lib/concurrent/agent.rb', line 34 def rescue(clazz = nil, &block) unless block.nil? mutex.synchronize do @rescuers << Rescuer.new(clazz, block) end end return self end |
#validate(&block) ⇒ Object Also known as: validates, validate_with, validates_with
45 46 47 48 |
# File 'lib/concurrent/agent.rb', line 45 def validate(&block) @validator = block unless block.nil? return self end |