quiet spurious wakeups for accept() in Thread* models
[rainbows.git] / lib / rainbows / thread_pool.rb
bloba68fcc6dc7d9cb500e8c960d1831e1a3cc2e8730
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 do
31         Thread.new { LISTENERS.size == 1 ? sync_worker : async_worker }
32       end
34       while G.alive
35         # if any worker dies, something is serious wrong, bail
36         pool.each do |thr|
37           G.tick or break
38           thr.join(1) and G.quit!
39         end
40       end
41       join_threads(pool)
42     end
44     def sync_worker
45       s = LISTENERS.first
46       begin
47         c = Rainbows.sync_accept(s) and process_client(c)
48       rescue => e
49         Error.listen_loop(e)
50       end while G.alive
51     end
53     def async_worker
54       begin
55         # TODO: check if select() or accept() is a problem on large
56         # SMP systems under Ruby 1.9.  Hundreds of native threads
57         # all working off the same socket could be a thundering herd
58         # problem.  On the other hand, a thundering herd may not
59         # even incur as much overhead as an extra Mutex#synchronize
60         ret = IO.select(LISTENERS, nil, nil, 1) and ret.first.each do |s|
61           s = Rainbows.accept(s) and process_client(s)
62         end
63       rescue Errno::EINTR
64       rescue => e
65         Error.listen_loop(e)
66       end while G.alive
67     end
69     def join_threads(threads)
70       G.quit!
71       threads.delete_if do |thr|
72         G.tick
73         thr.alive? ? thr.join(0.01) : true
74       end until threads.empty?
75     end
77   end
78 end