coolio: rename deferred_response => response_pipe
[rainbows.git] / lib / rainbows / thread_spawn.rb
blobacdaa6922f980f7e4ef3b87efde3f5734134c342
1 # -*- encoding: binary -*-
2 require 'thread'
4 # Spawns a new thread for every client connection we accept().  This
5 # model is recommended for platforms like Ruby 1.8 where spawning new
6 # threads is inexpensive.
8 # This model should provide a high level of compatibility with all
9 # Ruby implementations, and most libraries and applications.
10 # Applications running under this model should be thread-safe
11 # but not necessarily reentrant.
13 # If you're connecting to external services and need to perform DNS
14 # lookups, consider using the "resolv-replace" library which replaces
15 # parts of the core Socket package with concurrent DNS lookup
16 # capabilities
18 module Rainbows::ThreadSpawn
19   include Rainbows::Base
20   include Rainbows::WorkerYield
22   def accept_loop(klass) #:nodoc:
23     lock = Mutex.new
24     limit = worker_connections
25     LISTENERS.each do |l|
26       klass.new(l) do |l|
27         begin
28           if lock.synchronize { G.cur >= limit }
29             worker_yield
30           elsif c = l.kgio_accept
31             klass.new(c) do |c|
32               begin
33                 lock.synchronize { G.cur += 1 }
34                 process_client(c)
35               ensure
36                 lock.synchronize { G.cur -= 1 }
37               end
38             end
39           end
40         rescue => e
41           Rainbows::Error.listen_loop(e)
42         end while G.alive
43       end
44     end
45     sleep 1 while G.tick || lock.synchronize { G.cur > 0 }
46   end
48   def worker_loop(worker) #:nodoc:
49     init_worker_process(worker)
50     accept_loop(Thread)
51   end
52 end