Thread Safety: Class Variables in Ruby

后端 未结 3 591
悲哀的现实
悲哀的现实 2020-12-04 15:22

Performing writes/reads on class variables in Ruby is not thread safe. Performing writes/reads on instance variables appears to be thread safe. That said, is it thread safe

3条回答
  •  再見小時候
    2020-12-04 16:21

    Examples 2 and 3 are exactly the same. They are not thread-safety at all.

    Please see the example Below.

    class Foo
      def self.bar
        @bar ||= create_no
      end
    
      def self.create_no
        no = rand(10000)
        sleep 1
        no
      end
    end
    
    10.times.map do
      Thread.new do
        puts "bar is #{Foo.bar}"
      end
    end.each(&:join)
    

    It's result is not same. The result is same when using mutex as below.

    class Foo
      @mutex = Mutex.new
    
      def self.bar
        @mutex.synchronize {
          @bar ||= create_no
        }
      end
    
      def self.create_no
        no = rand(10000)
        sleep 1
        no
      end
    end
    
    10.times.map do
      Thread.new do
        puts "bar is #{Foo.bar}"
      end
    end.each(&:join)
    

    It is run on CRuby 2.3.0.

提交回复
热议问题