Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ||= in Ruby thread safe?

Not sure if threads safety even applies to ||=.

Was originally reading about ActiveSupport::Memoizable and wondered about thread safety there.

like image 364
sent-hil Avatar asked Mar 24 '12 15:03

sent-hil


People also ask

Are Ruby hashes thread-safe?

Unfortunately, Ruby doesn't ship with any thread-safe Array or Hash implementations. The core Array and Hash classes are not thread-safe by default, nor should they be.

Is Ruby logger thread-safe?

Yes, but even though only one thread runs at a time that doesn't make multi-threaded Ruby code thread-safe as what should be atomic operations can span multiple statements.

Is rails Cache thread-safe?

Keep it in memory thread_mattr_accessor method which makes it easy to build a trivial thread-safe cache service. Rails' implementation ensures every thread has its own storage location for cached_value ; therefore this should be thread-safe (assuming #compute_value can safely run both concurrently and in parallel).

Is rails single threaded?

Rails as a framework is thread-safe. So, the answer is yes! The second link that you posted here names many of the Rails servers that don't do well with multi-threading. He later mentions that nginx is the way to go (it is definitely the most popular one and highly recommended).


2 Answers

This great post on thread safety concepts in Ruby by Luca Guidi shows that ||= is not thread-safe (at least in MRI).

like image 101
907th Avatar answered Sep 30 '22 19:09

907th


It depends on the implementation. Be aware that x ||= y expands to x || x = y, and that x = y is only executed if x is either false or nil.

With that said, the C implementation of the Ruby language should be completely thread safe.

YARV uses native threads in order to implement concurrency, which do run in true parallel. However, in order to maintain backward compatibility, a global, interpreter-wide lock was introduced.

JRuby, however, imposes no internal locking on your code, so you must manually synchronize your calls when needed.

See another answer I've given about the subject for more details. Also, read this excellent answer by Jörg W Mittag for a more in-depth look at the threading models of the various Ruby implementations.

like image 20
Matheus Moreira Avatar answered Sep 30 '22 17:09

Matheus Moreira