Class: Narou::Worker

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/web/worker.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeWorker

Returns a new instance of Worker.



14
15
16
17
18
19
20
# File 'lib/web/worker.rb', line 14

def initialize
  @queue = Queue.new
  @size = 0
  @mutex = Mutex.new
  @worker_thread = nil
  @push_server = Narou::PushServer.instance
end

Instance Attribute Details

#sizeObject (readonly)

Returns the value of attribute size.



12
13
14
# File 'lib/web/worker.rb', line 12

def size
  @size
end

Class Method Details

.push(&block) ⇒ Object



62
63
64
# File 'lib/web/worker.rb', line 62

def self.push(&block)
  instance.push(&block)
end

.push_as_system_worker(&block) ⇒ Object

システム用のワーカー追加。内部カウントは増やさない



58
59
60
# File 'lib/web/worker.rb', line 58

def self.push_as_system_worker(&block)
  instance.push(false, &block)
end

Instance Method Details

#countdownObject



82
83
84
85
86
# File 'lib/web/worker.rb', line 82

def countdown
  @mutex.synchronize do
    @size -= 1
  end
end

#countupObject



76
77
78
79
80
# File 'lib/web/worker.rb', line 76

def countup
  @mutex.synchronize do
    @size += 1
  end
end

#notification_queueObject



72
73
74
# File 'lib/web/worker.rb', line 72

def notification_queue
  @push_server.send_all("notification.queue" => @size)
end

#push(counting = true, &block) ⇒ Object



66
67
68
69
70
# File 'lib/web/worker.rb', line 66

def push(counting = true, &block)
  countup if counting
  notification_queue
  @queue.push(block: block, counting: counting)
end

#running?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/web/worker.rb', line 22

def running?
  !@worker_thread.!
end

#startObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/web/worker.rb', line 26

def start
  return if running?
  @worker_thread = Thread.new do
    loop do
      begin
        q = @queue.pop
        q[:block].call
      rescue SystemExit
      rescue Exception => e
        # Workerスレッド内での例外は表示するだけしてスレッドは生かしたままにする
        STDOUT.puts $@.shift + ": #{e.message} (#{e.class})"
        $@.each do |b|
          STDOUT.puts "  from #{b}"
        end
      ensure
        if q[:counting]
          countdown
          notification_queue
        end
      end
    end
  end
end

#stopObject



50
51
52
53
# File 'lib/web/worker.rb', line 50

def stop
  @worker_thread.kill if @worker_thread
  @worker_thread = nil
end