Class: ThreadPool::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/tpkg/thread_pool.rb

Instance Method Summary collapse

Constructor Details

#initialize(thread_queue) ⇒ Worker

Returns a new instance of Worker.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/tpkg/thread_pool.rb', line 21

def initialize(thread_queue)
  @block = nil
  @mutex = Mutex.new
  @cv = ConditionVariable.new
  @queue = thread_queue
  @running = true
  @thread = Thread.new do
    @mutex.synchronize do
      while @running
        @cv.wait(@mutex)
        block = get_block
        if block
          @mutex.unlock
          block.call
          @mutex.lock
          reset_block
        end
        @queue << self
      end
    end
  end
end

Instance Method Details

#busy?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/tpkg/thread_pool.rb', line 65

def busy?
  @mutex.synchronize { !@block.nil? }
end

#get_blockObject



48
49
50
# File 'lib/tpkg/thread_pool.rb', line 48

def get_block
  @block
end

#nameObject



44
45
46
# File 'lib/tpkg/thread_pool.rb', line 44

def name
  @thread.inspect
end

#reset_blockObject



61
62
63
# File 'lib/tpkg/thread_pool.rb', line 61

def reset_block
  @block = nil
end

#set_block(block) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/tpkg/thread_pool.rb', line 52

def set_block(block)
  @mutex.synchronize do
    raise RuntimeError, "Thread already busy." if @block
    @block = block
    # Signal the thread in this class, that there's a job to be done
    @cv.signal
  end
end

#stopObject



69
70
71
72
73
74
75
# File 'lib/tpkg/thread_pool.rb', line 69

def stop
  @mutex.synchronize do
    @running = false
    @cv.signal
  end
  @thread.join
end