这个 ruby 代码线程安全吗?
这段代码是线程安全的吗?看起来应该如此,因为 @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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码正在使用 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.
不,Ruby 中的赋值是原子的。
No, assignment in Ruby is atomic.
假设线程创建 + 代码块评估每次都发生在不到 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.