gpt4 book ai didi

multithreading - Threads.@spawn 和 Threads.@threads 有什么区别?

转载 作者:行者123 更新时间:2023-12-03 12:44:47 27 4
gpt4 key购买 nike

我是一名对 Julia 语言感兴趣的新手程序员。文档( https://docs.julialang.org/en/v1/base/multi-threading/ )说 Threads.@threads 用于“for”循环和 theads.@spawn 将给定任务放置在任何可用线程上。我的理解是 Threads.@threads 本质上是同步的,而threads.@spawn 方法是异步的,需要更多的计划来实现(即使用 fetch() 方法)。

在我在网上找到的使用两者的代码中,我似乎看到两者可以互换使用(从我的角度来看)。对于新手程序员来说,这两者在概念上的区别是什么?我们应该如何/何时实现它们?另外,它们可以互补吗?

最佳答案

考虑:

function withthreads()
arr = zeros(Int, 10)
Threads.@threads for i in 1:10
sleep(3 * rand())
arr[i] = i
end
println("with @threads: $arr")
end


function withspawn()
arr = zeros(Int, 10)
for i in 1:10
Threads.@spawn begin
sleep(3 * rand())
arr[i] = i
end
end
println("with @spawn: $arr")
end

function withsync()
arr = zeros(Int, 10)
@sync begin
for i in 1:10
Threads.@spawn begin
sleep(3 * rand())
arr[i] = i
end
end
end
println("with @sync: $arr")
end

withthreads()
withspawn()
withsync()

输出:
with @threads: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
with @spawn: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
with @sync: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

所以@threads 管理分配给 julia 的线程池,并为 for 循环的每次迭代最多产生一个线程(可能多次使用相同的线程进行多次迭代,顺序为每个线程完成分配的迭代,如果迭代次数比线程多),并且还同步线程,直到所有线程都完成后才退出 for 块。 @spawn 只生成一个任务线程并立即返回到主任务,因此一旦所有任务生成,块就可以退出,甚至在它们完成工作之前(因此数组 arr 中的零保持为 0)。

关于multithreading - Threads.@spawn 和 Threads.@threads 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61905127/

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