Is ||= in Ruby thread safe?

后端 未结 2 479
轻奢々
轻奢々 2020-12-17 21:43

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

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

2条回答
  •  再見小時候
    2020-12-17 22:26

    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.

提交回复
热议问题