DRY setting of rack.multithread
[rainbows.git] / lib / rainbows / thread_pool.rb
blobc742e5d743804780cc93fffe4d38ac422accfe5f
1 # -*- encoding: binary -*-
3 module Rainbows
5   # Implements a worker thread pool model.  This is suited for platforms
6   # like Ruby 1.9, where the cost of dynamically spawning a new thread
7   # for every new client connection is higher than with the ThreadSpawn
8   # model.
9   #
10   # This model should provide a high level of compatibility with all
11   # Ruby implementations, and most libraries and applications.
12   # Applications running under this model should be thread-safe
13   # but not necessarily reentrant.
14   #
15   # Applications using this model are required to be thread-safe.
16   # Threads are never spawned dynamically under this model.  If you're
17   # connecting to external services and need to perform DNS lookups,
18   # consider using the "resolv-replace" library which replaces parts of
19   # the core Socket package with concurrent DNS lookup capabilities.
20   #
21   # This model probably less suited for many slow clients than the
22   # others and thus a lower +worker_connections+ setting is recommended.
24   module ThreadPool
26     include Base
28     def worker_loop(worker)
29       init_worker_process(worker)
30       pool = (1..worker_connections).map { new_worker_thread }
31       m = 0
33       while LISTENERS.first && master_pid == Process.ppid
34         pool.each do |thr|
35           worker.tmp.chmod(m = 0 == m ? 1 : 0)
36           # if any worker dies, something is serious wrong, bail
37           thr.join(timeout) and break
38         end
39       end
40       join_threads(pool, worker)
41     end
43     def new_worker_thread
44       Thread.new {
45         begin
46           begin
47             ret = IO.select(LISTENERS, nil, nil, timeout) or next
48             ret.first.each do |sock|
49               begin
50                 process_client(sock.accept_nonblock)
51               rescue Errno::EAGAIN, Errno::ECONNABORTED
52               end
53             end
54           rescue Errno::EINTR
55             next
56           rescue Errno::EBADF, TypeError
57             break
58           end
59         rescue Object => e
60           listen_loop_error(e)
61         end while ! Thread.current[:quit] && LISTENERS.first
62       }
63     end
65   end
66 end