【发布时间】:2014-10-28 15:17:00
【问题描述】:
我已经用 ruby 编写了一些代码来通过线程池处理数组中的项目。在这个过程中,我预先分配了一个与传入数组大小相同的结果数组。在线程池中,我在预分配数组中分配项目,但这些项目的索引保证是唯一的。考虑到这一点,我是否需要在作业周围加上 Mutex#synchronize?
例子:
SIZE = 1000000000
def collect_via_threadpool(items, pool_count = 10)
processed_items = Array.new(items.count, nil)
index = -1
length = items.length
mutex = Mutex.new
items_mutex = Mutex.new
[pool_count, length, 50].min.times.collect do
Thread.start do
while (i = mutex.synchronize{index = index + 1}) < length do
processed_items[i] = yield(items[i])
# ^ do I need to synchronize around this? `processed_items` is preallocated
end
end
end.each(&:join)
processed_items
end
items = collect_via_threadpool(SIZE.times.to_a, 100) do |item|
item.to_s
end
raise unless items.size == SIZE
items.each_with_index do |item, index|
raise unless item.to_i == index
end
puts 'success'
(此测试代码需要很长时间才能运行,但似乎每次都打印“成功”。)
为了安全起见,我似乎想用Mutex#synchronize 包围Array#[]=,但我的问题是:
在 Ruby 的规范中这段代码是否被定义为安全的?
【问题讨论】:
-
这取决于您要使用的 Ruby 实现。 MRI Ruby(经典之一)具有全局解释器锁。我不认为 Ruby 本身对此有任何保证,尽管我不能给出一个好的报价(这就是为什么它不是一个答案)。
标签: ruby arrays thread-safety assignment-operator lockless