about summary refs log tree commit homepage
path: root/lib/rainbows/coolio_thread_pool.rb
blob: 0e616a6665b1e70bd6b2709d846ce2dee171ad92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# -*- encoding: binary -*-

# A combination of the Coolio and ThreadPool models.  This allows Ruby
# Thread-based concurrency for application processing.  It DOES NOT
# expose a streamable "rack.input" for upload processing within the
# app.  DevFdResponse should be used with this class to proxy
# asynchronous responses.  All network I/O between the client and
# server are handled by the main thread and outside of the core
# application dispatch.
#
# Unlike ThreadPool, Cool.io makes this model highly suitable for
# slow clients and applications with medium-to-slow response times
# (I/O bound), but less suitable for sleepy applications.
#
# This concurrency model is designed for Ruby 1.9, and Ruby 1.8
# users are NOT advised to use this due to high CPU usage.
#
# === :pool_size vs worker_connections
#
# In your Rainbows! config block, you may specify a Thread pool size
# to limit your application concurrency independently of
# worker_connections.
#
#   Rainbows! do
#     use :CoolioThreadPool, :pool_size => 50
#     worker_connections 100
#   end
#
# In extremely rare cases, this may be combined with Rainbows::AppPool
# if you have different concurrency capabilities for different parts of
# your Rack application.
module Rainbows::CoolioThreadPool
  # :stopdoc:
  autoload :Client, 'rainbows/coolio_thread_pool/client'
  extend Rainbows::PoolSize
  #:startdoc:
  include Rainbows::Coolio::Core

  def init_worker_threads(master, queue) # :nodoc:
    Rainbows::O[:pool_size].times.map do
      Thread.new do
        begin
          client = queue.pop
          master << [ client, client.app_response ]
        rescue => e
          Rainbows::Error.listen_loop(e)
        end while true
      end
    end
  end

  def init_worker_process(worker) # :nodoc:
    super
    cloop = Coolio::Loop.default
    master = Rainbows::Coolio::Master.new(Queue.new).attach(cloop)
    queue = Client.const_set(:QUEUE, Queue.new)
    threads = init_worker_threads(master, queue)
    Watcher.new(threads).attach(cloop)
    logger.info "CoolioThreadPool pool_size=#{Rainbows::O[:pool_size]}"
  end
end
# :enddoc:
require 'rainbows/coolio_thread_pool/watcher'