cleanup and refactor error handling
[rainbows.git] / lib / rainbows / thread_spawn.rb
blob73a4107325b8ca2517d24d683a9bc53bd52f5a84
1 # -*- encoding: binary -*-
2 module Rainbows
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.
7   #
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.
12   #
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 ThreadSpawn
20     include Base
22     def worker_loop(worker)
23       init_worker_process(worker)
24       threads = ThreadGroup.new
25       limit = worker_connections
27       begin
28         ret = begin
29           G.tick or break
30           IO.select(LISTENERS, nil, nil, 1) or next
31         rescue Errno::EINTR
32           retry
33         rescue Errno::EBADF, TypeError
34           break
35         end
36         G.tick
38         ret.first.each do |l|
39           # Sleep if we're busy, another less busy worker process may
40           # take it for us if we sleep. This is gross but other options
41           # still suck because they require expensive/complicated
42           # synchronization primitives for _every_ case, not just this
43           # unlikely one.  Since this case is (or should be) uncommon,
44           # just busy wait when we have to.
45           while threads.list.size > limit # unlikely
46             sleep(0.1) # hope another process took it
47             break # back to IO.select
48           end
49           begin
50             threads.add(Thread.new(l.accept_nonblock) {|c| process_client(c) })
51           rescue Errno::EAGAIN, Errno::ECONNABORTED
52           end
53         end
54       rescue => e
55         Error.listen_loop(e)
56       end while true
57       join_threads(threads.list)
58     end
60   end
61 end