"how to know what is not thread-safe in ruby?" Code Answer


none of the core data structures are thread safe. the only one i know of that ships with ruby is the queue implementation in the standard library (require 'thread'; q = queue.new).

mri's gil does not save us from thread safety issues. it only makes sure that two threads cannot run ruby code at the same time, i.e. on two different cpus at the exact same time. threads can still be paused and resumed at any point in your code. if you write code like @n = 0; 3.times { thread.start { 100.times { @n += 1 } } } e.g. mutating a shared variable from multiple threads, the value of the shared variable afterwards is not deterministic. the gil is more or less a simulation of a single core system, it does not change the fundamental issues of writing correct concurrent programs.

even if mri had been single-threaded like node.js you would still have to think about concurrency. the example with the incremented variable would work fine, but you can still get race conditions where things happen in non-deterministic order and one callback clobbers the result of another. single threaded asynchronous systems are easier to reason about, but they are not free from concurrency issues. just think of an application with multiple users: if two users hit edit on a post at more or less the same time, spend some time editing the post and then hit save, whose changes will be seen by a third user later when they read that same post?

in ruby, as in most other concurrent runtimes, anything that is more than one operation is not thread safe. @n += 1 is not thread safe, because it is multiple operations. @n = 1 is thread safe because it is one operation (it's lots of operations under the hood, and i would probably get into trouble if i tried to describe why it's "thread safe" in detail, but in the end you will not get inconsistent results from assignments). @n ||= 1, is not and no other shorthand operation + assignment is either. one mistake i've made many times is writing return unless @started; @started = true, which is not thread safe at all.

i don't know of any authoritative list of thread safe and non-thread safe statements for ruby, but there is a simple rule of thumb: if an expression only does one (side-effect free) operation it is probably thread safe. for example: a + b is ok, a = b is also ok, and a.foo(b) is ok, if the method foo is side-effect free (since just about anything in ruby is a method call, even assignment in many cases, this goes for the other examples too). side-effects in this context means things that change state. def foo(x); @x = x; end is not side-effect free.

one of the hardest things about writing thread safe code in ruby is that all core data structures, including array, hash and string, are mutable. it's very easy to accidentally leak a piece of your state, and when that piece is mutable things can get really screwed up. consider the following code:

class thing
  attr_reader :stuff

  def initialize(initial_stuff)
    @stuff = initial_stuff
    @state_lock = mutex.new

  def add(item)
    @state_lock.synchronize do
      @stuff << item

a instance of this class can be shared between threads and they can safely add things to it, but there's a concurrency bug (it's not the only one): the internal state of the object leaks through the stuff accessor. besides being problematic from the encapsulation perspective, it also opens up a can of concurrency worms. maybe someone takes that array and passes it on to somewhere else, and that code in turn thinks it now owns that array and can do whatever it wants with it.

another classic ruby example is this:

standard_options = {:color => 'red', :count => 10}

def find_stuff
  @some_service.load_things('stuff', standard_options)

find_stuff works fine the first time it's used, but returns something else the second time. why? the load_things method happens to think it owns the options hash passed to it, and does color = options.delete(:color). now the standard_options constant doesn't have the same value anymore. constants are only constant in what they reference, they do not guarantee the constancy of the data structures they refer to. just think what would happen if this code was run concurrently.

if you avoid shared mutable state (e.g. instance variables in objects accessed by multiple threads, data structures like hashes and arrays accessed by multiple threads) thread safety isn't so hard. try to minimize the parts of your application that are accessed concurrently, and focus your efforts there. iirc, in a rails application, a new controller object is created for every request, so it is only going to get used by a single thread, and the same goes for any model objects you create from that controller. however, rails also encourages the use of global variables (user.find(...) uses the global variable user, you may think of it as only a class, and it is a class, but it is also a namespace for global variables), some of these are safe because they are read only, but sometimes you save things in these global variables because it is convenient. be very careful when you use anything that is globally accessible.

it's been possible to run rails in threaded environments for quite a while now, so without being a rails expert i would still go so far as to say that you don't have to worry about thread safety when it comes to rails itself. you can still create rails applications that aren't thread safe by doing some of the things i mention above. when it comes other gems assume that they are not thread safe unless they say that they are, and if they say that they are assume that they are not, and look through their code (but just because you see that they go things like @n ||= 1 does not mean that they are not thread safe, that's a perfectly legitimate thing to do in the right context -- you should instead look for things like mutable state in global variables, how it handles mutable objects passed to its methods, and especially how it handles options hashes).

finally, being thread unsafe is a transitive property. anything that uses something that is not thread safe is itself not thread safe.

By Tom Luo on January 15 2022

Answers related to “how to know what is not thread-safe in ruby?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.