这个 ruby​​ 代码线程安全吗?

发布于 2024-09-02 22:37:12 字数 433 浏览 8 评论 0原文

这段代码是线程安全的吗?看起来应该如此,因为 @myvar 永远不会从多个线程分配(假设块在 <1 秒内完成)。

但是我是否需要担心第二个块在写入时尝试读取 @myvar 的情况?

require 'rubygems'
require 'eventmachine'

@myvar = Time.now.to_i

EventMachine.run do

  EventMachine.add_periodic_timer(1) do
    EventMachine.defer do
      @myvar = Time.now.to_i # some calculation and reassign
    end
  end

  EventMachine.add_periodic_timer(0.5) do
    puts @myvar
  end

end

Is this code threadsafe? It seems like it should be, because @myvar will never be assigned from multiple threads (assuming block completes in < 1s).

But do I need to be worried about a situation where the second block is trying to read @myvar as it's being written?

require 'rubygems'
require 'eventmachine'

@myvar = Time.now.to_i

EventMachine.run do

  EventMachine.add_periodic_timer(1) do
    EventMachine.defer do
      @myvar = Time.now.to_i # some calculation and reassign
    end
  end

  EventMachine.add_periodic_timer(0.5) do
    puts @myvar
  end

end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

高冷爸爸 2024-09-09 22:37:12

您的代码正在使用 EventMachine,它仅使用线程进行 IO,并在单个中执行所有代码处理线。 EventMachine 专为您的目的而设计,因此所有变量访问在设计上都是线程安全的,无需在代码中进行额外检查。

不仅赋值是安全的(即使它是原子的),而且数据结构的操作也是安全的,并且不受竞争条件的影响。

Your code is using EventMachine, which uses threads for IO only, and does all code processing in a single thread. EventMachine is designed exactly for your purpose, so all variable access is by design thread safe, with no additional checks required in your code.

Not only is assignment safe (even though it's atomic) but manipulation of data structures are also safe and not subject to race conditions.

怪我太投入 2024-09-09 22:37:12

但是我是否需要担心第二个块在写入时尝试读取 @myvar 的情况?

不,Ruby 中的赋值是原子的。

But do I need to be worried about a situation where the second block is trying to read @myvar as it's being written?

No, assignment in Ruby is atomic.

执手闯天涯 2024-09-09 22:37:12

假设线程创建 + 代码块评估每次都发生在不到 1 秒的时间内,是的。否则,不,它不是线程安全的。

我认为值得一提的一件事是,显然你的例子是人为的;但是,根据您的实际代码,可能值得根据您的目的检查 Revactor 。它是一个参与者框架,使用轻量级不可抢占的执行线程。因此,许多常见的线程安全问题确实被排除在外,因为没有两个参与者可以同时运行。

只是一个想法。

Assuming that the thread creation + evaluation of your code block happens in less than 1 second every time, yes. Otherwise, no it is not thread safe.

One thing I think worth mentioning, is that obviously your example is contrived; however, depending on your actual code, it may be worth checking out Revactor for your purposes. It's an actor framework, that uses lightweight non-preemptable threads of execution. As a result, a lot of the common thread safety issues do go out of the window, since no two actors can be running at the same time.

Just a thought.

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