1
votes

I tried to run the example from https://docs.julialang.org/en/v1/manual/parallel-computing/#Channels-and-RemoteChannels-1 Just copy-pasted commands to my julia console. I am using version 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

It gave the following error:

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

Why it crashed on worker 4? I assumed the while loop should run only on master.

1

1 Answers

0
votes

The problem is that line:

n = n - 1

should be

global n = n - 1

This is unrelated to workers but new scope rules in Julia 1.0 (see https://docs.julialang.org/en/latest/manual/variables-and-scoping/#Local-Scope-1).

The example in the manual should be fixed.

Edit: the example is fixed on master https://docs.julialang.org/en/v1.1-dev/manual/parallel-computing/, but was not backported.