请考虑:
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中的零仍然保持不变)。
@threads
会生成和启动Julia时设置的线程数一样多的线程。特别地,它会将迭代任务均匀地分配给各个线程。 - Bogumił Kamiński