我正在使用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
以特殊的方式处理。