Class: Actuator::FiberPool

Inherits:
Object
  • Object
show all
Defined in:
lib/actuator/fiber_pool.rb

Constant Summary collapse

MAX_FIBERS =
10000

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.busy_countObject (readonly)

Returns the value of attribute busy_count.



13
14
15
# File 'lib/actuator/fiber_pool.rb', line 13

def busy_count
  @busy_count
end

Class Method Details

.create_new_fiberObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/actuator/fiber_pool.rb', line 47

def create_new_fiber
  Fiber.new do |job|
    fiber = Fiber.current
    while true
      #if !job || !job.is_a?(Job)
      #  Log.error "Job #{fiber.last_job ? fiber.last_job.id : -1} fiber resumed after ending and being released to the pool - #{job.inspect}"
      #end
      job.fiber = fiber
      fiber.job = job
      job.job_started
      begin
        job.block.call
      rescue JobKilledException
        # We use a cached exception to avoid the overhead of a catch block since fibers should almost never be killed
      rescue => ex
        Log.error "#{ex.class} while running job: #{ex.message}\n#{ex.backtrace.join "\n"}"
        raise ex
      rescue SystemExit
        break
      end
      job.job_ended
      #fiber.last_job = job
      if @queued_jobs.empty?
        @busy_count -= 1
        fiber.job = nil
        @idle_fibers << fiber
        job = Fiber.yield
      else
        job = @queued_jobs.shift
      end
    end
  end
end

.queue(whois = nil, &block) ⇒ Object

Job will be queued if MAX_FIBERS are already active



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/actuator/fiber_pool.rb', line 29

def queue(whois=nil, &block)
  job = Job.new
  job.block = block
  job.whois = whois

  if @busy_count >= MAX_FIBERS
    @queued_jobs << job
    #puts "[FiberPool] There are already #@busy_count/#{MAX_FIBERS} busy fibers, queued job #{job.id}"
    return false
  end

  @busy_count += 1
  fiber = @idle_fibers.pop || create_new_fiber
  fiber.resume(job)

  job
end

.run(whois = nil, &block) ⇒ Object

Always starts fiber immediately - ignores MAX_FIBERS (can cause pool to grow beyond limit)



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/actuator/fiber_pool.rb', line 16

def run(whois=nil, &block)
  job = Job.new
  job.block = block
  job.whois = whois

  @busy_count += 1
  fiber = @idle_fibers.pop || create_new_fiber
  fiber.resume(job)

  job
end