Skip to content

Commit 40a4cc3

Browse files
committed
Allow to insert throttle into chain
1 parent c1d0dd9 commit 40a4cc3

File tree

2 files changed

+28
-11
lines changed

2 files changed

+28
-11
lines changed

lib/concurrent/edge/promises.rb

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2031,10 +2031,12 @@ def initialize(max)
20312031
@Queue = Queue.new
20322032
end
20332033

2034-
def limit(ready = nil, &block)
2034+
def limit(future = nil, &block)
20352035
# TODO (pitr-ch 11-Jun-2016): triggers should allocate resources when they are to be required
2036+
trigger = future ? future & get_event : get_event
2037+
20362038
if block_given?
2037-
block.call(get_event).on_resolution! { done }
2039+
block.call(trigger).on_resolution! { done }
20382040
else
20392041
get_event
20402042
end
@@ -2067,4 +2069,12 @@ def get_event
20672069
end
20682070
end
20692071
end
2072+
2073+
class Promises::AbstractEventFuture < Synchronization::Object
2074+
2075+
def throttle(throttle, &throttled_future)
2076+
throttle.limit(self, &throttled_future)
2077+
end
2078+
2079+
end
20702080
end

spec/concurrent/promises_spec.rb

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -496,19 +496,26 @@ def behaves_as_delay(delay, value)
496496

497497
describe 'Throttling' do
498498
specify do
499-
throttle = Concurrent::Throttle.new 3
499+
max_tree = Concurrent::Throttle.new 3
500500
counter = Concurrent::AtomicFixnum.new
501+
testing = -> do
502+
counter.increment
503+
sleep 0.01
504+
# returns less then 3 since it's throttled
505+
counter.decrement
506+
end
507+
501508
expect(Concurrent::Promises.zip(
502509
*12.times.map do |i|
503-
throttle.limit do |trigger|
504-
trigger.then do
505-
counter.increment
506-
sleep 0.01
507-
counter.decrement
508-
end
509-
end
510+
max_tree.limit { |trigger| trigger.then &testing }
511+
end).value.all? { |v| v < 3 }).to be_truthy
512+
513+
expect(Concurrent::Promises.zip(
514+
*12.times.map do |i|
515+
Concurrent::Promises.
516+
fulfilled_future(i).
517+
throttle(max_tree) { |trigger| trigger.then &testing }
510518
end).value.all? { |v| v < 3 }).to be_truthy
511519
end
512520
end
513-
514521
end

0 commit comments

Comments
 (0)