coolio_thread_*: lazy load Rainbows::Coolio::Client
[rainbows.git] / lib / rainbows / coolio_thread_pool.rb
blob3d32bfb0efb180180c6cc50b30bc228ab23fcb2a
1 # -*- encoding: binary -*-
3 # A combination of the Coolio and ThreadPool models.  This allows Ruby
4 # Thread-based concurrency for application processing.  It DOES NOT
5 # expose a streamable "rack.input" for upload processing within the
6 # app.  DevFdResponse should be used with this class to proxy
7 # asynchronous responses.  All network I/O between the client and
8 # server are handled by the main thread and outside of the core
9 # application dispatch.
11 # Unlike ThreadPool, Cool.io makes this model highly suitable for
12 # slow clients and applications with medium-to-slow response times
13 # (I/O bound), but less suitable for sleepy applications.
15 # This concurrency model is designed for Ruby 1.9, and Ruby 1.8
16 # users are NOT advised to use this due to high CPU usage.
17 module Rainbows::CoolioThreadPool
18   # :stopdoc:
19   autoload :Client, 'rainbows/coolio_thread_pool/client'
20   DEFAULTS = {
21     :pool_size => 20, # same default size as ThreadPool (w/o Coolio)
22   }
23   #:startdoc:
25   def self.setup # :nodoc:
26     o = Rainbows::O
27     DEFAULTS.each { |k,v| o[k] ||= v }
28     Integer === o[:pool_size] && o[:pool_size] > 0 or
29       raise ArgumentError, "pool_size must a be an Integer > 0"
30   end
31   include Rainbows::Coolio::Core
33   def init_worker_threads(master, queue) # :nodoc:
34     Rainbows::O[:pool_size].times.map do
35       Thread.new do
36         begin
37           client = queue.pop
38           master << [ client, client.app_response ]
39         rescue => e
40           Rainbows::Error.listen_loop(e)
41         end while true
42       end
43     end
44   end
46   def init_worker_process(worker) # :nodoc:
47     super
48     cloop = Coolio::Loop.default
49     master = Rainbows::Coolio::Master.new(Queue.new).attach(cloop)
50     queue = Client.const_set(:QUEUE, Queue.new)
51     threads = init_worker_threads(master, queue)
52     Watcher.new(threads).attach(cloop)
53     logger.info "CoolioThreadPool pool_size=#{Rainbows::O[:pool_size]}"
54   end
55 end
56 # :enddoc:
57 require 'rainbows/coolio_thread_pool/watcher'