||= 在 Ruby 线程中安全吗? [英] Is ||= in Ruby thread safe?
问题描述
不确定线程安全是否适用于 ||=
.
Not sure if threads safety even applies to ||=
.
最初阅读的是关于 ActiveSupport::Memoizable 并想知道那里的线程安全性.
Was originally reading about ActiveSupport::Memoizable and wondered about thread safety there.
推荐答案
这取决于实现.请注意 x ||= y
扩展为 x ||x = y
,并且 x = y
仅在 x
为 false
或 nil
时执行>.
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
.
话虽如此,Ruby 语言的 C 实现应该是完全线程安全的.
With that said, the C implementation of the Ruby language should be completely thread safe.
YARV 使用本机线程来实现并发,确实以真正的并行方式运行.但是,为了保持向后兼容性,引入了全局、解释器范围的锁.
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 不会对您的代码施加内部锁定,因此您必须在需要时手动同步您的调用.
JRuby, however, imposes no internal locking on your code, so you must manually synchronize your calls when needed.
有关详细信息,请参阅我针对该主题给出的另一个答案.此外,请阅读 Jörg W Mittag 的这个优秀回答,以更深入地了解各种 Ruby 实现的线程模型.
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.
这篇关于||= 在 Ruby 线程中安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!