Class: RestCore::ThreadPool

Inherits:
Object
  • Object
show all
Includes:
RestCore
Defined in:
lib/rest-core/thread_pool.rb

Defined Under Namespace

Classes: Queue, Task

Constant Summary

Constants included from RestCore

ASYNC, CLIENT, DRY, FAIL, HIJACK, LOG, PROMISE, REQUEST_HEADERS, REQUEST_METHOD, REQUEST_PATH, REQUEST_PAYLOAD, REQUEST_QUERY, REQUEST_URI, RESPONSE_BODY, RESPONSE_HEADERS, RESPONSE_KEY, RESPONSE_SOCKET, RESPONSE_STATUS, Simple, TIMER, Universal, VERSION

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RestCore

eagerload, id

Constructor Details

#initialize(client_class) ⇒ ThreadPool

Returns a new instance of ThreadPool.



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

def initialize client_class
  @client_class = client_class
  @queue        = Queue.new
  @mutex        = Mutex.new
  @workers      = []
  @waiting      = 0
end

Instance Attribute Details

#client_classObject (readonly)

Returns the value of attribute client_class.



63
64
65
# File 'lib/rest-core/thread_pool.rb', line 63

def client_class
  @client_class
end

#workersObject (readonly)

Returns the value of attribute workers.



63
64
65
# File 'lib/rest-core/thread_pool.rb', line 63

def workers
  @workers
end

Class Method Details

.[](client_class) ⇒ Object



59
60
61
# File 'lib/rest-core/thread_pool.rb', line 59

def self.[] client_class
  (@pools ||= {})[client_class] ||= new(client_class)
end

Instance Method Details

#defer(promise_mutex, &job) ⇒ Object



89
90
91
92
93
94
95
96
# File 'lib/rest-core/thread_pool.rb', line 89

def defer promise_mutex, &job
  mutex.synchronize do
    task = Task.new(job, promise_mutex)
    queue << task
    spawn_worker if waiting < queue.size && workers.size < max_size
    task
  end
end

#idle_timeObject



85
86
87
# File 'lib/rest-core/thread_pool.rb', line 85

def idle_time
  client_class.pool_idle_time
end

#inspectObject



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

def inspect
  "#<#{self.class.name} client_class=#{client_class}>"
end

#max_sizeObject



81
82
83
# File 'lib/rest-core/thread_pool.rb', line 81

def max_size
  client_class.pool_size
end

#shutdownObject

Block on shutting down, and should not add more jobs while shutting down



105
106
107
108
109
# File 'lib/rest-core/thread_pool.rb', line 105

def shutdown
  workers.size.times{ trim(true) }
  workers.first.join && trim(true) until workers.empty?
  mutex.synchronize{ queue.clear }
end

#sizeObject



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

def size
  workers.size
end

#trim(force = false) ⇒ Object



98
99
100
101
102
# File 'lib/rest-core/thread_pool.rb', line 98

def trim force=false
  mutex.synchronize do
    queue << lambda{ |_| false } if force || waiting > 0
  end
end