fix various warnings with "check-warnings" target
[rainbows.git] / lib / rainbows / thread_spawn.rb
blob30e143e2a5d4dcfbb9068f0c7ff8bf5a8316221c
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     nr = 0
26     LISTENERS.each do |l|
27       klass.new do
28         begin
29           if lock.synchronize { nr >= limit }
30             worker_yield
31           elsif client = l.kgio_accept
32             klass.new(client) do |c|
33               begin
34                 lock.synchronize { nr += 1 }
35                 c.process_loop
36               ensure
37                 lock.synchronize { nr -= 1 }
38               end
39             end
40           end
41         rescue => e
42           Rainbows::Error.listen_loop(e)
43         end while Rainbows.alive
44       end
45     end
46     sleep 1 while Rainbows.tick || lock.synchronize { nr > 0 }
47   end
49   def worker_loop(worker) #:nodoc:
50     init_worker_process(worker)
51     accept_loop(Thread)
52   end
53 end