Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this ruby code thread safe?

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
like image 912
Ben K. Avatar asked Jan 23 '26 04:01

Ben K.


2 Answers

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.

like image 109
TelegramSam Avatar answered Jan 25 '26 12:01

TelegramSam


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.

like image 36
matsadler Avatar answered Jan 25 '26 11:01

matsadler