EventMachine 中是否会出现竞争条件?
"run"
块是否在 EM 中作为一个整体执行(没有上下文切换)?在这个例子中,if
子句中是否会存在竞争条件?
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
Does "run"
block executed as a whole in EM (without a context switch)? And in this example, will be there a race condition in the if
clause?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,EventMachine 是单线程的,因此除非您引入线程,否则实际上不应该存在任何竞争条件。
事件循环模型意味着您可以快速顺序执行小而简单的操作,而不是需要自己的线程的长而阻塞的方法。因此,您永远不应该并行执行两段代码。
您有责任在您定义的点频繁地对事件循环进行控制。
EventMachine, by default, is single threaded, so there really shouldn't be any race conditions unless you're introducing threads.
An event-loop model means you perform small, simple actions in rapid sequence instead of long, blocking methods that require their own threads. As such you should never have two pieces of code executing in parallel.
It is your responsibility to yield control to the event-loop frequently at points you define.