thread_spawn: fix up stupidly complicated loop
[rainbows.git] / lib / rainbows / thread_spawn.rb
blob40b37aafd51bfe9de3d4a704a3bc28316563794b
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 = IO.select(LISTENERS, nil, nil, 1) and
29           ret.first.each do |l|
30             if threads.list.size > limit # unlikely
31               # Sleep if we're busy, another less busy worker process may
32               # take it for us if we sleep. This is gross but other options
33               # still suck because they require expensive/complicated
34               # synchronization primitives for _every_ case, not just this
35               # unlikely one.  Since this case is (or should be) uncommon,
36               # just busy wait when we have to.
37               sleep(0.1) # hope another process took it
38               break # back to IO.select
39             end
40             c = begin
41               l.accept_nonblock
42             rescue Errno::EAGAIN, Errno::ECONNABORTED
43             end or next
44             threads.add(Thread.new { process_client(c) })
45           end
46       rescue Errno::EINTR
47         retry
48       rescue Errno::EBADF, TypeError
49         break
50       rescue => e
51         Error.listen_loop(e)
52       end while G.tick
53       join_threads(threads.list)
54     end
56   end
57 end