Class: ThreadPool::Worker
- Inherits:
-
Object
- Object
- ThreadPool::Worker
- Defined in:
- lib/thread_pool.rb
Instance Method Summary collapse
- #busy? ⇒ Boolean
- #get_block ⇒ Object
-
#initialize(thread_queue) ⇒ Worker
constructor
A new instance of Worker.
- #name ⇒ Object
- #reset_block ⇒ Object
- #set_block(block) ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize(thread_queue) ⇒ Worker
Returns a new instance of Worker.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/thread_pool.rb', line 5 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
49 50 51 |
# File 'lib/thread_pool.rb', line 49 def busy? @mutex.synchronize { !@block.nil? } end |
#get_block ⇒ Object
32 33 34 |
# File 'lib/thread_pool.rb', line 32 def get_block @block end |
#name ⇒ Object
28 29 30 |
# File 'lib/thread_pool.rb', line 28 def name @thread.inspect end |
#reset_block ⇒ Object
45 46 47 |
# File 'lib/thread_pool.rb', line 45 def reset_block @block = nil end |
#set_block(block) ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/thread_pool.rb', line 36 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 |
#stop ⇒ Object
53 54 55 56 57 58 59 |
# File 'lib/thread_pool.rb', line 53 def stop @mutex.synchronize do @running = false @cv.signal end @thread.join end |