线程安全:Ruby中的类变量 [英] Thread Safety: Class Variables in Ruby

查看:93
本文介绍了线程安全:Ruby中的类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中对类变量执行读写操作不是线程安全的.对实例变量执行写/读操作似乎是线程安全的.也就是说,对类或元类对象的实例变量执行写/读操作是否线程安全?

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 to perform write/reads on instance variables of a class or metaclass object?

就线程安全而言,这三个(人为)示例之间有何区别?

What are the differences between these three (contrived) examples in terms of thread safety?

示例1: 互斥

class BestUser # (singleton class)
  @@instance_lock = Mutex.new

  # Memoize instance
  def self.instance
    @@instance_lock.synchronize do
      @@instance ||= best
    end
  end
end

示例2: 实例变量存储

class BestUser # (singleton class)
  # Memoize instance
  def self.instance
    @instance ||= best
  end
end

示例3: 在METACLASS上即时存储变量

class BestUser # (singleton class)
  # Memoize instance
  class << self
    def instance
      @instance ||= best
    end
  end
end

推荐答案

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

示例2和示例3都具有实例变量,它们是等效的,并且它们是线程安全的,如@VincentXie所述.但是,这里有一个更好的例子来说明为什么它们不是这样:

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

因为实例变量在所有线程之间共享,如@VincentXie在其注释中所述.

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

PS:实例变量有时称为类实例变量",具体取决于使用它们的上下文:

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

当self是一个类时,它们是类的实例变量(class 实例变量).当自我是一个对象时,它们就是实例 对象的变量(实例变量). - WindorC对此问题的解答

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

这篇关于线程安全:Ruby中的类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆