EventMachine 中是否会出现竞争条件?

发布于 2025-01-08 05:47:24 字数 573 浏览 2 评论 0原文

"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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过期以后 2025-01-15 05:47:24

默认情况下,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文