Class: Af::ThreadPool

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

Defined Under Namespace

Classes: Worker

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size = 10, thread_class = Thread) ⇒ ThreadPool

Returns a new instance of ThreadPool.



48
49
50
51
52
53
# File 'lib/fiksu-af/thread_pool.rb', line 48

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

Instance Attribute Details

#max_sizeObject

Returns the value of attribute max_size.



45
46
47
# File 'lib/fiksu-af/thread_pool.rb', line 45

def max_size
  @max_size
end

#thread_classObject

Returns the value of attribute thread_class.



45
46
47
# File 'lib/fiksu-af/thread_pool.rb', line 45

def thread_class
  @thread_class
end

#workersObject (readonly)

Returns the value of attribute workers.



46
47
48
# File 'lib/fiksu-af/thread_pool.rb', line 46

def workers
  @workers
end

Instance Method Details

#busy?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/fiksu-af/thread_pool.rb', line 59

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

#create_workerObject



95
96
97
98
99
100
# File 'lib/fiksu-af/thread_pool.rb', line 95

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

#find_available_workerObject



87
88
89
# File 'lib/fiksu-af/thread_pool.rb', line 87

def find_available_worker
  free_worker || create_worker
end

#free_workerObject



91
92
93
# File 'lib/fiksu-af/thread_pool.rb', line 91

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

#joinObject



63
64
65
# File 'lib/fiksu-af/thread_pool.rb', line 63

def join
  sleep 0.01 while busy?
end

#process(&block) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/fiksu-af/thread_pool.rb', line 67

def process(&block)
  while true
    @mutex.synchronize do
      worker = find_available_worker 
      if worker
        return worker.set_block(block)
      end
    end
    sleep 0.01
  end
end

#sizeObject



55
56
57
# File 'lib/fiksu-af/thread_pool.rb', line 55

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

#wait_for_workerObject



79
80
81
82
83
84
85
# File 'lib/fiksu-af/thread_pool.rb', line 79

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