Thread Safety: Class Variables in Ruby

后端 未结 3 601
悲哀的现实
悲哀的现实 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 15:57

    Instance variables are not thread safe (and class variables are even less thread safe)

    Example 2 and 3, both with instance variables, are equivalent, and they are NOT thread safe, like @VincentXie stated. However, here is a better example to demonstrate why they are not:

    class Foo
      def self.bar(message)
        @bar ||= message
      end
    end
    
    t1 = Thread.new do
        puts "bar is #{Foo.bar('thread1')}"
    end
    
    t2 = Thread.new do
        puts "bar is #{Foo.bar('thread2')}"
    end
    
    sleep 2
    
    t1.join
    t2.join
    
    => bar is thread1
    => bar is thread1
    

    Because the instance variable is shared amongst all of the threads, like @VincentXie stated in his comment.

    PS: Instance variables are sometimes referred to as "class instance variables", depending on the context in which they are used:

    When self is a class, they are instance variables of classes(class instance variables). When self is a object, they are instance variables of objects(instance variables). - WindorC's answer to a question about this

提交回复
热议问题