You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Threads.@spawn与Threads.@threads执行耗时存在差异?

为什么Threads.@threads比@sync + Threads.@spawn执行耗时更长?

我测试了两段多线程代码,用julia -t4 test.jl执行后,发现withthreads()函数的执行耗时比withsync()长得多,原本预期两者耗时应该一致,想知道原因。

测试代码如下:

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

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

@time withthreads()
@time withsync()

执行后输出:

with @threads: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  3.174835 seconds (18.51 k allocations: 1.072 MiB, 2.52% compilation time)
with @sync: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1.035465 seconds (1.40 k allocations: 75.718 KiB, 1.28% compilation time)

内容的提问来源于stack exchange,提问作者Yi Wangtian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:26:22