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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With