我在 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'
(此测试代码需要很长时间才能运行,但似乎每次都打印“成功”。)
为了安全起见,我似乎想将其包围Array#[]=
起来Mutex#synchronize
,但我的问题是:
在 Ruby 的规范中,这段代码是否被定义为安全的?