Class: PoolParty::ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/poolparty/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.



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

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.



38
39
40
# File 'lib/poolparty/thread_pool.rb', line 38

def max_size
  @max_size
end

#workersObject (readonly)

Returns the value of attribute workers.



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

def workers
  @workers
end

Instance Method Details

#busy?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/poolparty/thread_pool.rb', line 51

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

#create_workerObject



87
88
89
90
91
92
# File 'lib/poolparty/thread_pool.rb', line 87

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

#find_available_workerObject



71
72
73
# File 'lib/poolparty/thread_pool.rb', line 71

def find_available_worker
  free_worker || create_worker
end

#free_workerObject



83
84
85
# File 'lib/poolparty/thread_pool.rb', line 83

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

#joinObject



55
56
57
# File 'lib/poolparty/thread_pool.rb', line 55

def join
  sleep 0.01 while busy?
end

#process(&block) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/poolparty/thread_pool.rb', line 59

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



47
48
49
# File 'lib/poolparty/thread_pool.rb', line 47

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

#wait_for_workerObject



75
76
77
78
79
80
81
# File 'lib/poolparty/thread_pool.rb', line 75

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