Is this ruby code thread safe?

Posted by Ben K. on Stack Overflow See other posts from Stack Overflow or by Ben K.
Published on 2010-05-28T02:57:50Z Indexed on 2010/05/28 3:01 UTC
Read the original article Hit count: 271

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about ruby

Related posts about threads