title: How to trace a deadlock in Ruby
body: <p>I use <a href="http://github.com/kwi/BrB/tree/master" rel="nofollow noreferrer">BrB</a> to share a datasource for various worker processes in Ruby 1.9 that I fork with <code>Process#fork</code>:</p>
  
  <pre><code>Thread.abort_on_exception = true
  
  fork do
    puts "Initializing data source process... (PID: #{Process.pid})"
    data = DataSource.new(files)
  
    BrB::Service.start_service(:object =&gt; data, :verbose =&gt; false, :host =&gt; host, :port =&gt; port)
    EM.reactor_thread.join
  end
  </code></pre>
  
  <p>The workers are forked as follows:</p>
  
  <pre><code>8.times do |t|  
    fork do
      data = BrB::Tunnel.create(nil, "brb://#{host}:#{port}", :verbose =&gt; false)
  
      puts "Launching #{threads_num} worker threads... (PID: #{Process.pid})"    
  
      threads = []
      threads_num.times { |i|
        threads &amp;lt;&amp;lt; Thread.new {
          while true
            begin
              worker = Worker.new(data, config)
  
            rescue OutOfTargetsError
              break
  
            rescue Exception =&gt; e
              puts "An unexpected exception was caught: #{e.class} =&gt; #{e}"
              sleep 5
  
            end
          end
        }
      }
      threads.each { |t| t.join }
  
      data.stop_service
      EM.stop
    end
  end
  </code></pre>
  
  <p>This works pretty much perfectly, but after around 10 minutes of running I get the following error:</p>
  
  <pre><code>bootstrap.rb:47:in `join': deadlock detected (fatal)
      from bootstrap.rb:47:in `block in &lt;main&gt;'
      from bootstrap.rb:39:in `fork'
      from bootstrap.rb:39:in `&lt;main&gt;'&lt;/pre&gt;
  </code></pre>
  
  <p>This error doesn't tell me much about where the deadlock is actually happening, it only points me to the <code>join</code> on the EventMachine thread.</p>
  
  <p>How do I trace back at which point the program locks up?</p>