为什么<<在Ruby中的数组上的操作不是原子的? [英] Why is the << operation on an array in Ruby not atomic?
问题描述
在Ruby中,如果array
被许多线程修改,则此代码不是线程安全的:
In Ruby, this code is not threadsafe if array
is modified by many threads:
array = []
array << :foo # many threads can run this code
为什么<<
操作不是线程安全的?
Why is the <<
operation not thread safe?
推荐答案
实际上,使用MRI(Matz的Ruby实现)的GIL(全局解释器锁)使任何纯C函数原子成为可能.
Actually using MRI (Matz's Ruby implementation) the GIL (Global Interpreter Lock) makes any pure C-function atomic.
由于Array#<<
在MRI中被实现为纯C代码,因此该操作将是原子的.但是请注意,这仅适用于MRI.在JRuby上不是这种情况.
Since Array#<<
is implemented as pure C-code in MRI, this operation will be atomic. But note this only applies to MRI. On JRuby this is not the case.
要完全了解发生了什么,我建议您阅读这两篇文章,这些文章对所有内容都进行了很好的解释:
To completely understand what is going on I suggest you read these two articles, which explains everything very well:
这篇关于为什么<<在Ruby中的数组上的操作不是原子的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!