gpt4 book ai didi

ruby - 修改线程之间公共(public)哈希的不同键是线程安全的吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:25 25 4
gpt4 key购买 nike

在线程之间共享 Ruby 哈希并在每个线程中修改它是否线程安全,保证每个线程修改不同的键(在执行前附加未确定的新哈希,键的数量) ?

我知道这样做不是线程安全的,如果线程修改同一个键,但是,我不确定如果它们修改不同的键是否安全。

例如下面是一个可能说明问题的示例程序:

#!/usr/bin/env ruby
# frozen_string_literal: true

array = [*1..100]
hash = {}
array.each do |element|
hash[element] = {}
end
threads = []
array.each do |element|
threads << Thread.new do
random = rand(1..100)
hash_new_keys = [*0..random]
hash[element] = {}
hash_new_keys.each do |key|
hash[element][key] = rand(1..10)
end
end
end
threads.each(&:join)

最佳答案

如果您使用 MRI,那么在不同线程中修改数组/散列是线程安全的。 GIL 保证同一时间只有一个线程处于事件状态。

这里有 5 个线程共享一个 Array 对象。每个线程将 nil 压入数组 1000 次:

array = []

5.times.map do
Thread.new do
1000.times do
array << nil
end
end
end.each(&:join)

puts array.size


$ ruby pushing_nil.rb
5000

$ jruby pushing_nil.rb
4446

$ rbx pushing_nil.rb
3088

Because MRI has a GIL, even when there are 5 threads running at once, only one thread is active at a time. In other words, things aren't truly parallel. JRuby and Rubinius don't have a GIL, so when you have 5 threads running, you really have 5 threads running in parallel across the available cores.

On the parallel Ruby implementations, the 5 threads are stepping through code that's not thread-safe. They end up interrupting each other and, ultimately, corrupting the underlying data.

引用 https://www.jstorimer.com/blogs/workingwithcode/8085491-nobody-understands-the-gil

关于ruby - 修改线程之间公共(public)哈希的不同键是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56899747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com