2012-02-22 37 views
2

"run"块在EM中是否作为一个整体执行(没有上下文切换)?在这个例子中,if条款中会出现竞争条件吗?EventMachine中是否存在竞争条件?

EventMachine.run { 
    @current_value = 0 
    EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080, :debug => true) do |ws| 
    ws.onopen { 
     @current_value += 1 
     if @current_value >= 4 # Race condition? 
     # Code Block 
     @current_value = 0 
     end 

     ws.onmessage { |msg| 
     # puts msg 
     } 

     ws.onclose { 
     # puts "disconnected" 
     } 
    } 
    end 
end 

回答

4

EventMachine默认情况下是单线程的,所以实际上不应该有任何竞争条件,除非你引入线程。

事件循环模型意味着您以快速序列执行小而简单的动作,而不是长时间的阻塞需要自己线程的方法。因此,你永远不应该有两段代码并行执行。

您有责任经常在您定义的点处对事件循环进行控制。