这段代码是线程安全的吗?看起来应该是这样,因为@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