Reputation: 924
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
Upvotes: 2
Views: 196
Reputation: 211540
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.
Upvotes: 4