noo*_*nly 7 multithreading julia
我是一名对 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()
Run Code Online (Sandbox Code Playgroud)
输出:
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]
Run Code Online (Sandbox Code Playgroud)
因此 @threads 管理分配给 julia 的线程池,并为 for 循环的每次迭代生成最多一个线程(可能在多次迭代中多次使用相同的线程,当每个线程完成其分配的迭代时,如果迭代次数比线程多),并且还同步线程,直到所有线程完成后才退出 for 块。@spawn 仅生成一个任务线程并立即返回到主任务,因此一旦生成所有任务,甚至在它们完成工作之前,就可以退出该块(因此数组 arr 中的零仍为 0)。
| 归档时间: |
|
| 查看次数: |
3479 次 |
| 最近记录: |