Class: Concurrent::Throttle
- Inherits:
-
Synchronization::Object
- Object
- Synchronization::Object
- Concurrent::Throttle
- Includes:
- PromisesIntegration
- Defined in:
- lib/concurrent/edge/throttle.rb
Overview
A tool manage concurrency level of future tasks.
Defined Under Namespace
Modules: PromisesIntegration
Instance Method Summary collapse
-
#initialize(limit) ⇒ Throttle
constructor
New throttle.
-
#limit ⇒ Integer
The limit.
-
#release ⇒ self
Has to be called once for each trigger after it is ok to execute another throttled task.
-
#throttled_block { ... } ⇒ Object
Blocks current thread until the block can be executed.
-
#to_s ⇒ String
(also: #inspect)
Short string representation.
-
#trigger ⇒ Promises::Event
New event which will be resolved when depending tasks can execute.
Methods included from PromisesIntegration
#throttled_future, #throttled_future_chain
Constructor Details
#initialize(limit) ⇒ Throttle
New throttle.
53 54 55 56 57 58 |
# File 'lib/concurrent/edge/throttle.rb', line 53 def initialize(limit) super() @Limit = limit self.can_run = limit @Queue = LockFreeQueue.new end |
Instance Method Details
#limit ⇒ Integer
Returns The limit.
61 62 63 |
# File 'lib/concurrent/edge/throttle.rb', line 61 def limit @Limit end |
#release ⇒ self
Has to be called once for each trigger after it is ok to execute another throttled task.
87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/concurrent/edge/throttle.rb', line 87 def release while true current_can_run = can_run if compare_and_set_can_run current_can_run, current_can_run + 1 if current_can_run < 0 Thread.pass until (trigger = @Queue.pop) trigger.resolve end return self end end end |
#throttled_block { ... } ⇒ Object
Blocks current thread until the block can be executed.
105 106 107 108 109 110 |
# File 'lib/concurrent/edge/throttle.rb', line 105 def throttled_block(&block) trigger.wait block.call ensure release end |
#to_s ⇒ String Also known as: inspect
Returns Short string representation.
113 114 115 |
# File 'lib/concurrent/edge/throttle.rb', line 113 def to_s format '<#%s:0x%x limit:%s can_run:%d>', self.class, object_id << 1, @Limit, can_run end |
#trigger ⇒ Promises::Event
New event which will be resolved when depending tasks can execute. Has to be used and after the critical work is done #release must be called exactly once.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/concurrent/edge/throttle.rb', line 69 def trigger while true current_can_run = can_run if compare_and_set_can_run current_can_run, current_can_run - 1 if current_can_run > 0 return Promises.resolved_event else event = Promises.resolvable_event @Queue.push event return event end end end end |