我想在我的所有4个处理器(intel i7(上运行函数f((,并获取rands和,如下所示:
using Distributed;
@everywhere function f()
return sum(rand(10000))
end
@sync for w in workers()
@async begin
res = @spawnat w f()
values[w-1] = fetch(res)
end
end
但是,得到以下错误:
ERROR: TaskFailedException
nested task error: MethodError: no method matching setindex!(::typeof(values), ::Float64, ::Int64)
Stacktrace:
[1] macro expansion
@ ./REPL[58]:4 [inlined]
[2] (::var"#68#70"{Channel{Any}, Int64})()
@ Main ./task.jl:411
Stacktrace:
[1] sync_end(c::Channel{Any})
@ Base ./task.jl:369
[2] top-level scope
@ task.jl:388
请指导我解决这个问题!
对于您的代码,最简单的方法是(假设Julia已使用-p 4
命令行参数运行,或者您已运行addprocs(4)
:
julia> values = @distributed (append!) for i in 1:4
[f()]
end
4-element Vector{Float64}:
5001.232864826896
4999.244031827526
4966.883114472259
5014.022690758762
如果你想自己做@spawn
,这个代码可以工作:
julia> values = Vector{Float64}(undef, 4);
julia> @sync for w in workers()
@async values[w-1] = fetch(@spawnat w f())
end
julia> values
4-element Vector{Float64}:
5029.967318172736
4993.1064528029
5016.491407076979
5062.0706219606345
然而,您的代码大多不起作用,因为values
的类型不是Vector{Float64}
。以下是如何复制您的错误:
julia> vv()=0
vv (generic function with 1 method)
julia> vv[1]=11
ERROR: MethodError: no method matching setindex!(::typeof(vv), ::Int64, ::Int64)