class Concurrent::Throttle

A tool manage concurrency level of future tasks.

@!macro throttle.example.then_throttled_by @!macro throttle.example.throttled_future @!macro throttle.example.throttled_future_chain @!macro throttle.example.throttled_block @!macro warn.edge

Public Class Methods

new(limit) click to toggle source

New throttle. @param [Integer] limit

Calls superclass method
# File lib-edge/concurrent/edge/throttle.rb, line 61
def initialize(limit)
  super()
  @Limit       = limit
  self.can_run = limit
  @Queue       = LockFreeQueue.new
end

Public Instance Methods

inspect()
Alias for: to_s
limit() click to toggle source

@return [Integer] The limit.

# File lib-edge/concurrent/edge/throttle.rb, line 69
def limit
  @Limit
end
release() click to toggle source

Has to be called once for each trigger after it is ok to execute another throttled task. @return [self] @see trigger

# File lib-edge/concurrent/edge/throttle.rb, line 95
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
        # release called after trigger which pushed a trigger, busy wait is ok
        Thread.pass until (trigger = @Queue.pop)
        trigger.resolve
      end
      return self
    end
  end
end
throttled_block(&block) click to toggle source

Blocks current thread until the block can be executed. @yield to throttled block @yieldreturn [Object] is used as a result of the method @return [Object] the result of the block @!macro throttle.example.throttled_block

# File lib-edge/concurrent/edge/throttle.rb, line 114
def throttled_block(&block)
  trigger.wait
  block.call
ensure
  release
end
to_s() click to toggle source

@return [String] Short string representation.

Calls superclass method
# File lib-edge/concurrent/edge/throttle.rb, line 122
def to_s
  format '%s limit:%s can_run:%d>', super[0..-2], @Limit, can_run
end
Also aliased as: inspect
trigger() click to toggle source

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. @return [Promises::Event] @see release

# File lib-edge/concurrent/edge/throttle.rb, line 77
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