Julia RemoteChanel示例给出了UndefVarError

时间:2018-12-04 21:54:33

标签: julia

我尝试从https://docs.julialang.org/en/v1/manual/parallel-computing/#Channels-and-RemoteChannels-1运行示例 只需将粘贴的命令复制到我的julia控制台即可。我正在使用1.0.0版

   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.   
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.0.0 (2018-08-08)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release  
|__/                   |

julia> nprocs()
5

julia> const results = RemoteChannel(()->Channel{Tuple}(32));

julia> const jobs = RemoteChannel(()->Channel{Int}(32));

julia> @everywhere function do_work(jobs, results) # define work function everywhere
              while true
                  job_id = take!(jobs)
                  exec_time = rand()
                  sleep(exec_time) # simulates elapsed time doing actual work
                  put!(results, (job_id, exec_time, myid()))
              end
          end

julia> function make_jobs(n)
             for i in 1:n
                 put!(jobs, i)
             end
         end;

julia> n = 12
12

julia> @async make_jobs(n);

julia> for p in workers() # start tasks on the workers to process requests in parallel
             remote_do(do_work, p, jobs, results)
         end

julia> @elapsed while n > 0 # print out results
              job_id, exec_time, where = take!(results)
              println("$job_id finished in $(round(exec_time; digits=2)) seconds on worker $where")
              n = n - 1
          end

它给出了以下错误:

4 finished in 0.46 seconds on worker 4
ERROR: UndefVarError: n not defined
Stacktrace:
[1] macro expansion at ./REPL[9]:4 [inlined]
[2] top-level scope at ./util.jl:213 [inlined]
[3] top-level scope at ./none:0

为什么它在工人4上崩溃了?我以为while循环应该只在master上运行。

1 个答案:

答案 0 :(得分:0)

问题在于那一行:

n = n - 1

应该是

global n = n - 1

这与工人无关,但是在Julia 1.0中有了新的范围规则(请参见https://docs.julialang.org/en/latest/manual/variables-and-scoping/#Local-Scope-1)。

手册中的示例应固定。

编辑:该示例已固定在主https://docs.julialang.org/en/v1.1-dev/manual/parallel-computing/上,但未反向移植。