views:

138

answers:

3

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
A: 

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.

jer
A: 

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.

matsadler
just out of curiosity, are there languages where assignment isn't atomic?
Ben K.
+2  A: 

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.

TelegramSam