rainbows.git  about / heads / tags
Unicorn for sleepy apps and slow clients
blob 30e8f69b5acdbb405dfadf71f610d74c7aa063df 2052 bytes (raw)
$ git show v0.3.0:lib/rainbows/thread_pool.rb	# shows this blob on the CLI

 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
64
65
 
# -*- encoding: binary -*-

module Rainbows

  # Implements a worker thread pool model.  This is suited for platforms
  # like Ruby 1.9, where the cost of dynamically spawning a new thread
  # for every new client connection is higher than with the ThreadSpawn
  # model.
  #
  # This model should provide a high level of compatibility with all
  # Ruby implementations, and most libraries and applications.
  # Applications running under this model should be thread-safe
  # but not necessarily reentrant.
  #
  # Applications using this model are required to be thread-safe.
  # Threads are never spawned dynamically under this model.  If you're
  # connecting to external services and need to perform DNS lookups,
  # consider using the "resolv-replace" library which replaces parts of
  # the core Socket package with concurrent DNS lookup capabilities.
  #
  # This model probably less suited for many slow clients than the
  # others and thus a lower +worker_connections+ setting is recommended.

  module ThreadPool

    include Base

    def worker_loop(worker)
      init_worker_process(worker)
      pool = (1..worker_connections).map { new_worker_thread }
      m = 0

      while G.alive && master_pid == Process.ppid
        pool.each do |thr|
          worker.tmp.chmod(m = 0 == m ? 1 : 0)
          # if any worker dies, something is serious wrong, bail
          thr.join(timeout) and break
        end
      end
      join_threads(pool, worker)
    end

    def new_worker_thread
      Thread.new {
        begin
          begin
            ret = IO.select(LISTENERS, nil, nil, 1) and
                  ret.first.each do |sock|
                    begin
                      process_client(sock.accept_nonblock)
                    rescue Errno::EAGAIN, Errno::ECONNABORTED
                    end
                  end
          rescue Errno::EINTR
          rescue Errno::EBADF, TypeError
            break
          end
        rescue Object => e
          listen_loop_error(e)
        end while G.alive
      }
    end

  end
end

git clone https://yhbt.net/rainbows.git