Class: ThreadPool

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

Defined Under Namespace

Classes: Worker

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size = 10) ⇒ ThreadPool

Returns a new instance of ThreadPool.



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

def initialize(max_size = 10)
  @max_size = max_size
  @workers = []
  @mutex = Mutex.new
end

Instance Attribute Details

#max_sizeObject

Returns the value of attribute max_size.



40
41
42
# File 'lib/thread_pool.rb', line 40

def max_size
  @max_size
end

#workersObject (readonly)

Returns the value of attribute workers.



41
42
43
# File 'lib/thread_pool.rb', line 41

def workers
  @workers
end

Instance Method Details

#busy?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/thread_pool.rb', line 53

def busy?
  @mutex.synchronize {@workers.any? {|w| w.busy?}}
end

#create_workerObject



81
82
83
84
85
86
# File 'lib/thread_pool.rb', line 81

def create_worker
  return nil if @workers.size >= @max_size
  worker = Worker.new
  @workers << worker
  worker
end

#find_available_workerObject



73
74
75
# File 'lib/thread_pool.rb', line 73

def find_available_worker
  @mutex.synchronize {free_worker || create_worker}
end

#free_workerObject



77
78
79
# File 'lib/thread_pool.rb', line 77

def free_worker
  @workers.each {|w| return w unless w.busy?}; nil
end

#joinObject



57
58
59
# File 'lib/thread_pool.rb', line 57

def join
  sleep 0.01 while busy?
end

#process(&block) ⇒ Object



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

def process(&block)
  wait_for_worker.set_block(block)
end

#sizeObject



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

def size
  @mutex.synchronize {@workers.size}
end

#wait_for_workerObject



65
66
67
68
69
70
71
# File 'lib/thread_pool.rb', line 65

def wait_for_worker
  while true
    worker = find_available_worker
    return worker if worker
    sleep 0.01
  end
end