title: Concurrent producer/consumer in Ruby
body: <p>I'm trying to implement something analogous to the producer consumer problem in Ruby. Here is my implementation:</p>
  
  <pre><code>class ProducerConsumerQueue
    def initialize
      @queue = []
      @queue_lock = Mutex.new
      @queue_write_lock = Mutex.new
      @queue_lock.lock
    end
  
    def produce product
      @queue_write_lock.synchronized do
        @queue &lt;&lt; product
        @queue_lock.unlock if @queue_lock.locked?
      end
    end
  
    def consume
      @queue_lock.lock
      @queue_write_lock.synchronized { @queue.pop }
    end
  end
  </code></pre>
  
  <p>I thought this would be a good implementation because</p>
  
  <ul>
  <li>Consumers can create and write their products whenever</li>
  <li>Consumers can block in the <code>consume</code> method when there is nothing to consume. </li>
  </ul>
  
  <p>The problem, however, is that this implementation does not work in Ruby. Apparently, you cannot lock a mutex in one thread, and then unlock it in another. Is there another way to do this?</p>
  
  <p>Thanks!</p>