Rails中的多线程:while循环阻止另一个方法调用

时间:2014-04-10 08:08:48

标签: ruby-on-rails multithreading deadlock puma

我正在使用Puma服务器来实现多线程。这是我的控制器:

class PhoneCallsController < ActionController::Base
  include ActionController::Live
  protect_from_forgery :except => :record_call

  # GET: Return messages to JavaScript pop-up
  def get_messages
      random_num = rand(65536)
      log "Start of get_messages, random id = #{random_num}"
      sleep 60
      #while session[:new_record_date]==session[:prev_record_date] do
      #  sleep 1
      #end
      session[:prev_record_date] = session[:new_record_date]
      render :status => :ok, :json => ['my message']
      log "End of get_messages, random id = #{random_num}"
  end

  # POST: Record a phone call. Called by PBX.
  def record_call
    log 'Start of record_call'

    data = Hash.from_xml(request.raw_post)
    pbx_data = data['PbxData']

    pc = PhoneCall.new({
                            :command => pbx_data['cmd'].strip,
                            :recipient_ip => pbx_data['RecipientIP'].strip,
                            :phone_num => pbx_data['PhoneNum'].strip
                        })
    pc.save!

    session[:new_record_date] = pc.created_at

    debug_text = "call received:\ncmd: #{pc.command}\nRecipientIP: #{pc.recipient_ip}\nPhoneNum: #{pc.phone_num}"

    log debug_text
    render :status => :ok, :text => debug_text

    log 'End of record_call'
  end

  # Test page to simulate PBX calls
  def call_test
  end

  # Test page to receive pop-up notifications
  def messages_test
  end

  private
  def log(msg)
    Rails.logger.info msg
    puts msg
  end
end

因此,有两种主要方法:get_messages由JavaScript调用,其任务返回结果,直到电话呼叫到达(连接应该保持)。

第二种方法 - 当回答呼叫时,PBX脚本会调用record_call

问题是 - 只在

sleep 60
get_messages中提到

,然后可以随时调用record_call方法,并且不会锁定整个所有内容。

但如果我用

替换此sleep 60
while session[:new_record_date]==session[:prev_record_date] do
  sleep 1
end

(应该如此) - 这个while循环阻止整个应用程序。

我做错了什么?为什么sleep没有阻止应用程序,但是当它被包装到while循环中时(假设它是一个无限循环),应用程序被锁定了?

我认为在我的情况下多线程并不是真正的多线程,并且sleep以特殊的方式处理。

0 个答案:

没有答案