Class: FloorManager::Workers

Inherits:
Object
  • Object
show all
Defined in:
lib/floormanager/workers.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*queue) ⇒ Workers

Returns a new instance of Workers.



4
5
6
7
8
# File 'lib/floormanager/workers.rb', line 4

def initialize(*queue)
  queue = *queue
  @queue = queue.kind_of?(FloorManager::Queue) ? queue : FloorManager::Queue.new(queue)
  @mutex = Mutex.new
end

Instance Attribute Details

#queueObject (readonly)

Returns the value of attribute queue.



9
10
11
# File 'lib/floormanager/workers.rb', line 9

def queue
  @queue
end

Instance Method Details

#checkin(*args) ⇒ Object



39
40
41
# File 'lib/floormanager/workers.rb', line 39

def checkin(*args)
  synchronize{@queue.checkin(*args)}
end

#checkoutObject



35
36
37
# File 'lib/floormanager/workers.rb', line 35

def checkout
  synchronize{@queue.checkout}
end

#failed(result = nil) ⇒ Object



60
61
62
# File 'lib/floormanager/workers.rb', line 60

def failed(result=nil)
  result(result, States::FAILED)
end

#halt(time) ⇒ Object



48
49
50
# File 'lib/floormanager/workers.rb', line 48

def halt(time)
  synchronize{sleep(time)}
end

#perform(options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/floormanager/workers.rb', line 11

def perform(options={})
  options = {:threads => 1, :timeout => false}.merge(options)
  threads = (0...options[:threads]).to_a.map do |thread_id|
    Thread.new do
      until queue.done?
        if item = checkout
          result = yield(item[:item])
          result = Result.new(result, (result.state rescue States::SUCCESS))
          item[:value] = result
          checkin(item, result.state)
        else
          Thread.pass
        end
      end
    end
  end
  if options[:timeout]
    threads.each{|t| t.join(options[:timeout])}
  else
    threads.each{|t| t.join}
  end
  @queue
end

#result(result, state = States::SUCCESS) ⇒ Object



52
53
54
# File 'lib/floormanager/workers.rb', line 52

def result(result, state=States::SUCCESS)
  Result.new(result, state)
end

#success(result) ⇒ Object



56
57
58
# File 'lib/floormanager/workers.rb', line 56

def success(result)
  result(result, States::SUCCESS)
end

#synchronizeObject Also known as: exclusively



43
44
45
# File 'lib/floormanager/workers.rb', line 43

def synchronize
  @mutex.synchronize{yield}
end