(1)查看当前是否是多核运行环境
julia> nprocs() # 一般默认的启动是单核
1
(2)如果不是,可以增加
julia> nprocs()
1
julia> addprocs(2) # 增加二个CPU核
2-element Array{Any,1}:
2
3
julia> nprocs()
3
(3)指定某个核去进行相应的计算
julia> r = remotecall(2, rand, 2, 2)
RemoteRef(2,1,2)
julia> fetch(r)
2x2 Array{Float64,2}:
0.307291 0.132549
0.279847 0.0266977
julia> s=remotecall(3, rand, 2, 2)
RemoteRef(3,1,4)
julia> fetch(s)
2x2 Array{Float64,2}:
0.906434 0.272713
0.910273 0.227246
julia> remotecall_fetch(2, getindex, r, 1, 1)
0.307290542962672
julia> remotecall_fetch(2, getindex, s, 2, 1)
0.9102734845481404
但remotecall或remotecall_fetch都有一个问题,即是核的位置是需要记住的。
julia> a=@spawn rand(2,2)
RemoteRef(2,1,12)
julia> b=@spawn maximum([2,2])
RemoteRef(3,1,13)
julia> c=@spawn minimum([2,1])
RemoteRef(2,1,14)
julia> fetch(a)
2x2 Array{Float64,2}:
0.634395 0.770792
0.882946 0.346484
julia> fetch(b)
2
julia> fetch(c)
1
(4)并行计算的顺序和单核的情况不一样
julia> @parallel [println("$i") for i =1:10]
From worker 3: 6
From worker 3: 7
From worker 3: 8
From worker 3: 9
From worker 3: 10
From worker 2: 1
From worker 2: 2
From worker 2: 3
From worker 2: 4
From worker 2: 5
10-element DArray{Any,1,Array{Any,1}}:
nothing
nothing
nothing
nothing
nothing
nothing
nothing
nothing
nothing
nothing
# 布置一个其它核运行的任务,等其计算后,再取过来。
julia> b=@parallel [i for i =1:10];
julia> fetch(b)
10-element DArray{Int64,1,Array{Int64,1}}:
1
2
3
4
5
6
7
8
9
10
可见,取过来的值,完全是有序的。