gpt4 book ai didi

multithreading - 使用 Threads.@threads 的意外行为?

转载 作者:行者123 更新时间:2023-12-03 12:45:18 28 4
gpt4 key购买 nike

在下面的代码中,内部循环创建一个全 1 的向量,然后将向量的每个值设置为 0。此向量的总和预计为 0。但是,如果我使用 Threads .@threads 在内循环上,有时不是。我是否违反了有关此代码的多线程规则?似乎内循环并不总是“完成”。我将 JULIA_NUM_THREADS 设置为 4。

N = 1000
M = 1000
for i in 1:N
test = trues(M)
Threads.@threads for j in 1:M
test[j] = 0
end
s = sum(test)
if s > 0
println("sum(M) was ", s, "!")
end
end
println("done!")

示例输出:

enter image description here

在外循环中使用Threads.@threads 似乎没有任何问题。我如何预测哪些地方可以使用 Threads.@threads 哪些地方不可以?

最佳答案

这是因为trues创建一个 BitArray ,其中 bool 值被有效地打包为 64 位 block 中的各个位。因此,对相邻索引的访问可能会很活跃。

这将在下面讨论 issue , 并应尽快记录 PR合并。

如果您使用其他数组类型,例如 Vector{Bool},问题就会消失:

N = 1000
M = 1000
for i in 1:N
test = ones(Bool, M) # creates a Vector{Bool}
Threads.@threads for j in 1:M
test[j] = 0
end
s = sum(test)
if s > 0
println("sum(M) was ", s, "!")
end
end
println("done!")

关于multithreading - 使用 Threads.@threads 的意外行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61218454/

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