title: EventMachine and Ruby Threads - what's really going on here?
body: <p>we use Rails and EventMachine together, and when using that combo with Passenger there is some very specific setup that needs to be done. After a lot of trial and error, I got EventMachine initialization working well, but I would like to understand the code a little better. As you can see below in this code snippet, our initializer checks for Passenger, and then checks if it's a forked process before restarting EventMachine.</p>
  
  <pre><code>if defined?(PhusionPassenger)
    PhusionPassenger.on_event(:starting_worker_process) do |forked|
    # for passenger, we need to avoid orphaned threads
      if forked &amp;&amp; EM.reactor_running?
        EM.stop
      end
      Thread.new {
        EM.run do
  </code></pre>
  
  <p>My question is related to the EM.reactor_running? and EM.stop commands. If Passenger has forked our process, why do I need to restart the EM reference in a new thread? If EM.reactor_running? returns true, what EM instance am I referencing? </p>
  
  <p>You can see the full initializer code on our blog here <a href="http://www.hiringthing.com/2011/11/04/eventmachine-with-rails.html" rel="noreferrer">http://www.hiringthing.com/2011/11/04/eventmachine-with-rails.html</a></p>