Class: LittleGhost::Subagents::Manager::Capacity

Inherits:
Object
  • Object
show all
Defined in:
lib/little_ghost/subagents/manager.rb

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(limit) ⇒ Capacity

Returns a new instance of Capacity.



147
148
149
150
151
# File 'lib/little_ghost/subagents/manager.rb', line 147

def initialize(limit)
  @available = limit
  @mutex = Mutex.new
  @condition = ConditionVariable.new
end

Instance Method Details

#synchronize(cancellation_token, deadline: nil) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/little_ghost/subagents/manager.rb', line 153

def synchronize(cancellation_token, deadline: nil)
  @mutex.synchronize do
    while @available.zero?
      cancellation_token.raise_if_cancelled!
      if deadline && Time.now >= deadline
        raise DeadlineExceededError, "The run deadline was reached"
      end

      timeout = deadline ? [deadline - Time.now, 0.05].min : 0.05
      @condition.wait(@mutex, [timeout, 0].max)
    end
    @available -= 1
  end

  begin
    yield
  ensure
    @mutex.synchronize do
      @available += 1
      @condition.signal
    end
  end
  true
end