Are Ruby class methods thread-safe? Are Ruby class methods thread-safe? ruby ruby

Are Ruby class methods thread-safe?


The local variables, such as your hash, are local to the particular invocation of the surrounding method. If two threads end up calling perform at the same time, then each call will get its own execution context and those won't overlap unless there are shared resources involved: instance variables (@hash), class variables (@@hash), globals ($hash), ... can cause concurrency problems. There's nothing to worry about thread-wise with something simple like your perform.

However, if perform was creating threads and you ended up with closures inside perform, then you could end up with several threads referencing the same local variables captured through the closures. So you do have to be careful about scope issues when you create threads but you don't have to worry about it when dealing with simple methods that only work with local variables.


Something being a "class method" (which is just a singleton method on a class object) doesn't make it any more thread-safe than it being an instance method.