425 lines
90 KiB
HTML
425 lines
90 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Parallel Computing · The Julia Language</title><script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
|
||
|
||
ga('create', 'UA-28835595-6', 'auto');
|
||
ga('send', 'pageview');
|
||
</script><link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css" rel="stylesheet" type="text/css"/><link href="https://fonts.googleapis.com/css?family=Lato|Roboto+Mono" rel="stylesheet" type="text/css"/><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css"/><script>documenterBaseURL=".."</script><script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js" data-main="../assets/documenter.js"></script><script src="../siteinfo.js"></script><script src="../../versions.js"></script><link href="../assets/highlightjs/default.css" rel="stylesheet" type="text/css"/><link href="../assets/documenter.css" rel="stylesheet" type="text/css"/></head><body><nav class="toc"><a href="../index.html"><img class="logo" src="../assets/logo.png" alt="The Julia Language logo"/></a><h1>The Julia Language</h1><select id="version-selector" onChange="window.location.href=this.value" style="visibility: hidden"></select><form class="search" action="../search.html"><input id="search-query" name="q" type="text" placeholder="Search docs"/></form><ul><li><a class="toctext" href="../index.html">Home</a></li><li><span class="toctext">Manual</span><ul><li><a class="toctext" href="introduction.html">Introduction</a></li><li><a class="toctext" href="getting-started.html">Getting Started</a></li><li><a class="toctext" href="variables.html">Variables</a></li><li><a class="toctext" href="integers-and-floating-point-numbers.html">Integers and Floating-Point Numbers</a></li><li><a class="toctext" href="mathematical-operations.html">Mathematical Operations and Elementary Functions</a></li><li><a class="toctext" href="complex-and-rational-numbers.html">Complex and Rational Numbers</a></li><li><a class="toctext" href="strings.html">Strings</a></li><li><a class="toctext" href="functions.html">Functions</a></li><li><a class="toctext" href="control-flow.html">Control Flow</a></li><li><a class="toctext" href="variables-and-scoping.html">Scope of Variables</a></li><li><a class="toctext" href="types.html">Types</a></li><li><a class="toctext" href="methods.html">Methods</a></li><li><a class="toctext" href="constructors.html">Constructors</a></li><li><a class="toctext" href="conversion-and-promotion.html">Conversion and Promotion</a></li><li><a class="toctext" href="interfaces.html">Interfaces</a></li><li><a class="toctext" href="modules.html">Modules</a></li><li><a class="toctext" href="documentation.html">Documentation</a></li><li><a class="toctext" href="metaprogramming.html">Metaprogramming</a></li><li><a class="toctext" href="arrays.html">Multi-dimensional Arrays</a></li><li><a class="toctext" href="linear-algebra.html">Linear algebra</a></li><li><a class="toctext" href="networking-and-streams.html">Networking and Streams</a></li><li class="current"><a class="toctext" href="parallel-computing.html">Parallel Computing</a><ul class="internal"><li><a class="toctext" href="#Code-Availability-and-Loading-Packages-1">Code Availability and Loading Packages</a></li><li><a class="toctext" href="#Data-Movement-1">Data Movement</a></li><li class="toplevel"><a class="toctext" href="#Global-variables-1">Global variables</a></li><li><a class="toctext" href="#Parallel-Map-and-Loops-1">Parallel Map and Loops</a></li><li><a class="toctext" href="#Synchronization-With-Remote-References-1">Synchronization With Remote References</a></li><li><a class="toctext" href="#Scheduling-1">Scheduling</a></li><li><a class="toctext" href="#Channels-1">Channels</a></li><li><a class="toctext" href="#Remote-References-and-AbstractChannels-1">Remote References and AbstractChannels</a></li><li><a class="toctext" href="#Channels-and-RemoteChannels-1">Channels and RemoteChannels</a></li><li><a class="toctext" href="#Remote-References-and-Distributed-Garbage-Collection-1">Remote References and Distributed Garbage Collection</a></li><li><a class="toctext" href="#man-shared-arrays-1">Shared Arrays</a></li><li><a class="toctext" href="#Shared-Arrays-and-Distributed-Garbage-Collection-1">Shared Arrays and Distributed Garbage Collection</a></li><li><a class="toctext" href="#ClusterManagers-1">ClusterManagers</a></li><li><a class="toctext" href="#Cluster-Managers-with-Custom-Transports-1">Cluster Managers with Custom Transports</a></li><li><a class="toctext" href="#Network-Requirements-for-LocalManager-and-SSHManager-1">Network Requirements for LocalManager and SSHManager</a></li><li><a class="toctext" href="#Cluster-Cookie-1">Cluster Cookie</a></li><li><a class="toctext" href="#Specifying-Network-Topology-(Experimental)-1">Specifying Network Topology (Experimental)</a></li><li><a class="toctext" href="#Multi-Threading-(Experimental)-1">Multi-Threading (Experimental)</a></li><li><a class="toctext" href="#@threadcall-(Experimental)-1">@threadcall (Experimental)</a></li></ul></li><li><a class="toctext" href="dates.html">Date and DateTime</a></li><li><a class="toctext" href="interacting-with-julia.html">Interacting With Julia</a></li><li><a class="toctext" href="running-external-programs.html">Running External Programs</a></li><li><a class="toctext" href="calling-c-and-fortran-code.html">Calling C and Fortran Code</a></li><li><a class="toctext" href="handling-operating-system-variation.html">Handling Operating System Variation</a></li><li><a class="toctext" href="environment-variables.html">Environment Variables</a></li><li><a class="toctext" href="embedding.html">Embedding Julia</a></li><li><a class="toctext" href="packages.html">Packages</a></li><li><a class="toctext" href="profile.html">Profiling</a></li><li><a class="toctext" href="stacktraces.html">Stack Traces</a></li><li><a class="toctext" href="performance-tips.html">Performance Tips</a></li><li><a class="toctext" href="workflow-tips.html">Workflow Tips</a></li><li><a class="toctext" href="style-guide.html">Style Guide</a></li><li><a class="toctext" href="faq.html">Frequently Asked Questions</a></li><li><a class="toctext" href="noteworthy-differences.html">Noteworthy Differences from other Languages</a></li><li><a class="toctext" href="unicode-input.html">Unicode Input</a></li></ul></li><li><span class="toctext">Standard Library</span><ul><li><a class="toctext" href="../stdlib/base.html">Essentials</a></li><li><a class="toctext" href="../stdlib/collections.html">Collections and Data Structures</a></li><li><a class="toctext" href="../stdlib/math.html">Mathematics</a></li><li><a class="toctext" href="../stdlib/numbers.html">Numbers</a></li><li><a class="toctext" href="../stdlib/strings.html">Strings</a></li><li><a class="toctext" href="../stdlib/arrays.html">Arrays</a></li><li><a class="toctext" href="../stdlib/parallel.html">Tasks and Parallel Computing</a></li><li><a class="toctext" href="../stdlib/linalg.html">Linear Algebra</a></li><li><a class="toctext" href="../stdlib/constants.html">Constants</a></li><li><a class="toctext" href="../stdlib/file.html">Filesystem</a></li><li><a class="toctext" href="../stdlib/io-network.html">I/O and Network</a></li><li><a class="toctext" href="../stdlib/punctuation.html">Punctuation</a></li><li><a class="toctext" href="../stdlib/sort.html">Sorting and Related Functions</a></li><li><a class="toctext" href="../stdlib/pkg.html">Package Manager Functions</a></li><li><a class="toctext" href="../stdlib/dates.html">Dates and Time</a></li><li><a class="toctext" href="../stdlib/iterators.html">Iteration utilities</a></li><li><a class="toctext" href="../stdlib/test.html">Unit Testing</a></li><li><a class="toctext" href="../stdlib/c.html">C Interface</a></li><li><a class="toctext" href="../stdlib/libc.html">C Standard Library</a></li><li><a class="toctext" href="../stdlib/libdl.html">Dynamic Linker</a></li><li><a class="toctext" href="../stdlib/profile.html">Profiling</a></li><li><a class="toctext" href="../stdlib/stacktraces.html">StackTraces</a></li><li><a class="toctext" href="../stdlib/simd-types.html">SIMD Support</a></li></ul></li><li><span class="toctext">Developer Documentation</span><ul><li><a class="toctext" href="../devdocs/reflection.html">Reflection and introspection</a></li><li><span class="toctext">Documentation of Julia's Internals</span><ul><li><a class="toctext" href="../devdocs/init.html">Initialization of the Julia runtime</a></li><li><a class="toctext" href="../devdocs/ast.html">Julia ASTs</a></li><li><a class="toctext" href="../devdocs/types.html">More about types</a></li><li><a class="toctext" href="../devdocs/object.html">Memory layout of Julia Objects</a></li><li><a class="toctext" href="../devdocs/eval.html">Eval of Julia code</a></li><li><a class="toctext" href="../devdocs/callconv.html">Calling Conventions</a></li><li><a class="toctext" href="../devdocs/compiler.html">High-level Overview of the Native-Code Generation Process</a></li><li><a class="toctext" href="../devdocs/functions.html">Julia Functions</a></li><li><a class="toctext" href="../devdocs/cartesian.html">Base.Cartesian</a></li><li><a class="toctext" href="../devdocs/meta.html">Talking to the compiler (the <code>:meta</code> mechanism)</a></li><li><a class="toctext" href="../devdocs/subarrays.html">SubArrays</a></li><li><a class="toctext" href="../devdocs/sysimg.html">System Image Building</a></li><li><a class="toctext" href="../devdocs/llvm.html">Working with LLVM</a></li><li><a class="toctext" href="../devdocs/stdio.html">printf() and stdio in the Julia runtime</a></li><li><a class="toctext" href="../devdocs/boundscheck.html">Bounds checking</a></li><li><a class="toctext" href="../devdocs/locks.html">Proper maintenance and care of multi-threading locks</a></li><li><a class="toctext" href="../devdocs/offset-arrays.html">Arrays with custom indices</a></li><li><a class="toctext" href="../devdocs/libgit2.html">Base.LibGit2</a></li><li><a class="toctext" href="../devdocs/require.html">Module loading</a></li></ul></li><li><span class="toctext">Developing/debugging Julia's C code</span><ul><li><a class="toctext" href="../devdocs/backtraces.html">Reporting and analyzing crashes (segfaults)</a></li><li><a class="toctext" href="../devdocs/debuggingtips.html">gdb debugging tips</a></li><li><a class="toctext" href="../devdocs/valgrind.html">Using Valgrind with Julia</a></li><li><a class="toctext" href="../devdocs/sanitizers.html">Sanitizer support</a></li></ul></li></ul></li></ul></nav><article id="docs"><header><nav><ul><li>Manual</li><li><a href="parallel-computing.html">Parallel Computing</a></li></ul><a class="edit-page" href="https://github.com/JuliaLang/julia/tree/d386e40c17d43b79fc89d3e579fc04547241787c/doc/src/manual/parallel-computing.md"><span class="fa"></span> Edit on GitHub</a></nav><hr/><div id="topbar"><span>Parallel Computing</span><a class="fa fa-bars" href="#"></a></div></header><h1><a class="nav-anchor" id="Parallel-Computing-1" href="#Parallel-Computing-1">Parallel Computing</a></h1><p>Most modern computers possess more than one CPU, and several computers can be combined together in a cluster. Harnessing the power of these multiple CPUs allows many computations to be completed more quickly. There are two major factors that influence performance: the speed of the CPUs themselves, and the speed of their access to memory. In a cluster, it's fairly obvious that a given CPU will have fastest access to the RAM within the same computer (node). Perhaps more surprisingly, similar issues are relevant on a typical multicore laptop, due to differences in the speed of main memory and the <a href="https://www.akkadia.org/drepper/cpumemory.pdf">cache</a>. Consequently, a good multiprocessing environment should allow control over the "ownership" of a chunk of memory by a particular CPU. Julia provides a multiprocessing environment based on message passing to allow programs to run on multiple processes in separate memory domains at once.</p><p>Julia's implementation of message passing is different from other environments such as MPI <a href="#footnote-1">[1]</a>. Communication in Julia is generally "one-sided", meaning that the programmer needs to explicitly manage only one process in a two-process operation. Furthermore, these operations typically do not look like "message send" and "message receive" but rather resemble higher-level operations like calls to user functions.</p><p>Parallel programming in Julia is built on two primitives: <em>remote references</em> and <em>remote calls</em>. A remote reference is an object that can be used from any process to refer to an object stored on a particular process. A remote call is a request by one process to call a certain function on certain arguments on another (possibly the same) process.</p><p>Remote references come in two flavors: <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> and <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a>.</p><p>A remote call returns a <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> to its result. Remote calls return immediately; the process that made the call proceeds to its next operation while the remote call happens somewhere else. You can wait for a remote call to finish by calling <a href="../stdlib/parallel.html#Base.wait"><code>wait()</code></a> on the returned <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a>, and you can obtain the full value of the result using <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a>.</p><p>On the other hand, <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> s are rewritable. For example, multiple processes can co-ordinate their processing by referencing the same remote <code>Channel</code>.</p><p>Each process has an associated identifier. The process providing the interactive Julia prompt always has an <code>id</code> equal to 1. The processes used by default for parallel operations are referred to as "workers". When there is only one process, process 1 is considered a worker. Otherwise, workers are considered to be all processes other than process 1.</p><p>Let's try this out. Starting with <code>julia -p n</code> provides <code>n</code> worker processes on the local machine. Generally it makes sense for <code>n</code> to equal the number of CPU cores on the machine.</p><pre><code class="language-julia">$ ./julia -p 2
|
||
|
||
julia> r = remotecall(rand, 2, 2, 2)
|
||
Future(2, 1, 4, Nullable{Any}())
|
||
|
||
julia> s = @spawnat 2 1 .+ fetch(r)
|
||
Future(2, 1, 5, Nullable{Any}())
|
||
|
||
julia> fetch(s)
|
||
2×2 Array{Float64,2}:
|
||
1.18526 1.50912
|
||
1.16296 1.60607</code></pre><p>The first argument to <a href="../stdlib/parallel.html#Base.Distributed.remotecall-Tuple{Any,Integer,Vararg{Any,N} where N}"><code>remotecall()</code></a> is the function to call. Most parallel programming in Julia does not reference specific processes or the number of processes available, but <a href="../stdlib/parallel.html#Base.Distributed.remotecall-Tuple{Any,Integer,Vararg{Any,N} where N}"><code>remotecall()</code></a> is considered a low-level interface providing finer control. The second argument to <a href="../stdlib/parallel.html#Base.Distributed.remotecall-Tuple{Any,Integer,Vararg{Any,N} where N}"><code>remotecall()</code></a> is the <code>id</code> of the process that will do the work, and the remaining arguments will be passed to the function being called.</p><p>As you can see, in the first line we asked process 2 to construct a 2-by-2 random matrix, and in the second line we asked it to add 1 to it. The result of both calculations is available in the two futures, <code>r</code> and <code>s</code>. The <a href="../stdlib/parallel.html#Base.Distributed.@spawnat"><code>@spawnat</code></a> macro evaluates the expression in the second argument on the process specified by the first argument.</p><p>Occasionally you might want a remotely-computed value immediately. This typically happens when you read from a remote object to obtain data needed by the next local operation. The function <a href="../stdlib/parallel.html#Base.Distributed.remotecall_fetch-Tuple{Any,Integer,Vararg{Any,N} where N}"><code>remotecall_fetch()</code></a> exists for this purpose. It is equivalent to <code>fetch(remotecall(...))</code> but is more efficient.</p><pre><code class="language-julia-repl">julia> remotecall_fetch(getindex, 2, r, 1, 1)
|
||
0.18526337335308085</code></pre><p>Remember that <a href="../stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}"><code>getindex(r,1,1)</code></a> is <a href="arrays.html#man-array-indexing-1">equivalent</a> to <code>r[1,1]</code>, so this call fetches the first element of the future <code>r</code>.</p><p>The syntax of <a href="../stdlib/parallel.html#Base.Distributed.remotecall-Tuple{Any,Integer,Vararg{Any,N} where N}"><code>remotecall()</code></a> is not especially convenient. The macro <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a> makes things easier. It operates on an expression rather than a function, and picks where to do the operation for you:</p><pre><code class="language-julia-repl">julia> r = @spawn rand(2,2)
|
||
Future(2, 1, 4, Nullable{Any}())
|
||
|
||
julia> s = @spawn 1 .+ fetch(r)
|
||
Future(3, 1, 5, Nullable{Any}())
|
||
|
||
julia> fetch(s)
|
||
2×2 Array{Float64,2}:
|
||
1.38854 1.9098
|
||
1.20939 1.57158</code></pre><p>Note that we used <code>1 .+ fetch(r)</code> instead of <code>1 .+ r</code>. This is because we do not know where the code will run, so in general a <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a> might be required to move <code>r</code> to the process doing the addition. In this case, <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a> is smart enough to perform the computation on the process that owns <code>r</code>, so the <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a> will be a no-op (no work is done).</p><p>(It is worth noting that <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a> is not built-in but defined in Julia as a <a href="metaprogramming.html#man-macros-1">macro</a>. It is possible to define your own such constructs.)</p><p>An important thing to remember is that, once fetched, a <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> will cache its value locally. Further <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a> calls do not entail a network hop. Once all referencing <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a>s have fetched, the remote stored value is deleted.</p><h2><a class="nav-anchor" id="Code-Availability-and-Loading-Packages-1" href="#Code-Availability-and-Loading-Packages-1">Code Availability and Loading Packages</a></h2><p>Your code must be available on any process that runs it. For example, type the following into the Julia prompt:</p><pre><code class="language-julia-repl">julia> function rand2(dims...)
|
||
return 2*rand(dims...)
|
||
end
|
||
|
||
julia> rand2(2,2)
|
||
2×2 Array{Float64,2}:
|
||
0.153756 0.368514
|
||
1.15119 0.918912
|
||
|
||
julia> fetch(@spawn rand2(2,2))
|
||
ERROR: RemoteException(2, CapturedException(UndefVarError(Symbol("#rand2"))
|
||
[...]</code></pre><p>Process 1 knew about the function <code>rand2</code>, but process 2 did not.</p><p>Most commonly you'll be loading code from files or packages, and you have a considerable amount of flexibility in controlling which processes load code. Consider a file, <code>DummyModule.jl</code>, containing the following code:</p><pre><code class="language-julia">module DummyModule
|
||
|
||
export MyType, f
|
||
|
||
mutable struct MyType
|
||
a::Int
|
||
end
|
||
|
||
f(x) = x^2+1
|
||
|
||
println("loaded")
|
||
|
||
end</code></pre><p>Starting Julia with <code>julia -p 2</code>, you can use this to verify the following:</p><ul><li><p><a href="../stdlib/base.html#Base.include"><code>include("DummyModule.jl")</code></a> loads the file on just a single process (whichever one executes the statement).</p></li><li><p><code>using DummyModule</code> causes the module to be loaded on all processes; however, the module is brought into scope only on the one executing the statement.</p></li><li><p>As long as <code>DummyModule</code> is loaded on process 2, commands like</p><pre><code class="language-julia">rr = RemoteChannel(2)
|
||
put!(rr, MyType(7))</code></pre><p>allow you to store an object of type <code>MyType</code> on process 2 even if <code>DummyModule</code> is not in scope on process 2.</p></li></ul><p>You can force a command to run on all processes using the <a href="../stdlib/parallel.html#Base.Distributed.@everywhere"><code>@everywhere</code></a> macro. For example, <code>@everywhere</code> can also be used to directly define a function on all processes:</p><pre><code class="language-julia-repl">julia> @everywhere id = myid()
|
||
|
||
julia> remotecall_fetch(()->id, 2)
|
||
2</code></pre><p>A file can also be preloaded on multiple processes at startup, and a driver script can be used to drive the computation:</p><pre><code class="language-none">julia -p <n> -L file1.jl -L file2.jl driver.jl</code></pre><p>The Julia process running the driver script in the example above has an <code>id</code> equal to 1, just like a process providing an interactive prompt.</p><p>The base Julia installation has in-built support for two types of clusters:</p><ul><li><p>A local cluster specified with the <code>-p</code> option as shown above.</p></li><li><p>A cluster spanning machines using the <code>--machinefile</code> option. This uses a passwordless <code>ssh</code> login to start Julia worker processes (from the same path as the current host) on the specified machines.</p></li></ul><p>Functions <a href="../stdlib/parallel.html#Base.Distributed.addprocs"><code>addprocs()</code></a>, <a href="../stdlib/parallel.html#Base.Distributed.rmprocs"><code>rmprocs()</code></a>, <a href="../stdlib/parallel.html#Base.Distributed.workers"><code>workers()</code></a>, and others are available as a programmatic means of adding, removing and querying the processes in a cluster.</p><p>Note that workers do not run a <code>.juliarc.jl</code> startup script, nor do they synchronize their global state (such as global variables, new method definitions, and loaded modules) with any of the other running processes.</p><p>Other types of clusters can be supported by writing your own custom <code>ClusterManager</code>, as described below in the <a href="parallel-computing.html#ClusterManagers-1">ClusterManagers</a> section.</p><h2><a class="nav-anchor" id="Data-Movement-1" href="#Data-Movement-1">Data Movement</a></h2><p>Sending messages and moving data constitute most of the overhead in a parallel program. Reducing the number of messages and the amount of data sent is critical to achieving performance and scalability. To this end, it is important to understand the data movement performed by Julia's various parallel programming constructs.</p><p><a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a> can be considered an explicit data movement operation, since it directly asks that an object be moved to the local machine. <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a> (and a few related constructs) also moves data, but this is not as obvious, hence it can be called an implicit data movement operation. Consider these two approaches to constructing and squaring a random matrix:</p><p>Method 1:</p><pre><code class="language-julia-repl">julia> A = rand(1000,1000);
|
||
|
||
julia> Bref = @spawn A^2;
|
||
|
||
[...]
|
||
|
||
julia> fetch(Bref);</code></pre><p>Method 2:</p><pre><code class="language-julia-repl">julia> Bref = @spawn rand(1000,1000)^2;
|
||
|
||
[...]
|
||
|
||
julia> fetch(Bref);</code></pre><p>The difference seems trivial, but in fact is quite significant due to the behavior of <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a>. In the first method, a random matrix is constructed locally, then sent to another process where it is squared. In the second method, a random matrix is both constructed and squared on another process. Therefore the second method sends much less data than the first.</p><p>In this toy example, the two methods are easy to distinguish and choose from. However, in a real program designing data movement might require more thought and likely some measurement. For example, if the first process needs matrix <code>A</code> then the first method might be better. Or, if computing <code>A</code> is expensive and only the current process has it, then moving it to another process might be unavoidable. Or, if the current process has very little to do between the <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a> and <code>fetch(Bref)</code>, it might be better to eliminate the parallelism altogether. Or imagine <code>rand(1000,1000)</code> is replaced with a more expensive operation. Then it might make sense to add another <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a> statement just for this step.</p><h1><a class="nav-anchor" id="Global-variables-1" href="#Global-variables-1">Global variables</a></h1><p>Expressions executed remotely via <code>@spawn</code>, or closures specified for remote execution using <code>remotecall</code> may refer to global variables. Global bindings under module <code>Main</code> are treated a little differently compared to global bindings in other modules. Consider the following code snippet:</p><pre><code class="language-julia-repl">A = rand(10,10)
|
||
remotecall_fetch(()->foo(A), 2)</code></pre><p>Note that <code>A</code> is a global variable defined in the local workspace. Worker 2 does not have a variable called <code>A</code> under <code>Main</code>. The act of shipping the closure <code>()->foo(A)</code> to worker 2 results in <code>Main.A</code> being defined on 2. <code>Main.A</code> continues to exist on worker 2 even after the call <code>remotecall_fetch</code> returns. Remote calls with embedded global references (under <code>Main</code> module only) manage globals as follows:</p><ul><li><p>New global bindings are created on destination workers if they are referenced as part of a remote call.</p></li><li><p>Global constants are declared as constants on remote nodes too.</p></li><li><p>Globals are re-sent to a destination worker only in the context of a remote call, and then only if its value has changed. Also, the cluster does not synchronize global bindings across nodes. For example:</p><pre><code class="language-julia">A = rand(10,10)
|
||
remotecall_fetch(()->foo(A), 2) # worker 2
|
||
A = rand(10,10)
|
||
remotecall_fetch(()->foo(A), 3) # worker 3
|
||
A = nothing</code></pre><p>Executing the above snippet results in <code>Main.A</code> on worker 2 having a different value from <code>Main.A</code> on worker 3, while the value of <code>Main.A</code> on node 1 is set to <code>nothing</code>.</p></li></ul><p>As you may have realized, while memory associated with globals may be collected when they are reassigned on the master, no such action is taken on the workers as the bindings continue to be valid. <a href="../stdlib/parallel.html#Base.Distributed.clear!-Tuple{CachingPool}"><code>clear!</code></a> can be used to manually reassign specific globals on remote nodes to <code>nothing</code> once they are no longer required. This will release any memory associated with them as part of a regular garbage collection cycle.</p><p>Thus programs should be careful referencing globals in remote calls. In fact, it is preferable to avoid them altogether if possible. If you must reference globals, consider using <code>let</code> blocks to localize global variables.</p><p>For example:</p><pre><code class="language-julia-repl">julia> A = rand(10,10);
|
||
|
||
julia> remotecall_fetch(()->A, 2);
|
||
|
||
julia> B = rand(10,10);
|
||
|
||
julia> let B = B
|
||
remotecall_fetch(()->B, 2)
|
||
end;
|
||
|
||
julia> @spawnat 2 whos();
|
||
|
||
julia> From worker 2: A 800 bytes 10×10 Array{Float64,2}
|
||
From worker 2: Base Module
|
||
From worker 2: Core Module
|
||
From worker 2: Main Module</code></pre><p>As can be seen, global variable <code>A</code> is defined on worker 2, but <code>B</code> is captured as a local variable and hence a binding for <code>B</code> does not exist on worker 2.</p><h2><a class="nav-anchor" id="Parallel-Map-and-Loops-1" href="#Parallel-Map-and-Loops-1">Parallel Map and Loops</a></h2><p>Fortunately, many useful parallel computations do not require data movement. A common example is a Monte Carlo simulation, where multiple processes can handle independent simulation trials simultaneously. We can use <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a> to flip coins on two processes. First, write the following function in <code>count_heads.jl</code>:</p><pre><code class="language-julia">function count_heads(n)
|
||
c::Int = 0
|
||
for i = 1:n
|
||
c += rand(Bool)
|
||
end
|
||
c
|
||
end</code></pre><p>The function <code>count_heads</code> simply adds together <code>n</code> random bits. Here is how we can perform some trials on two machines, and add together the results:</p><pre><code class="language-julia-repl">julia> @everywhere include("count_heads.jl")
|
||
|
||
julia> a = @spawn count_heads(100000000)
|
||
Future(2, 1, 6, Nullable{Any}())
|
||
|
||
julia> b = @spawn count_heads(100000000)
|
||
Future(3, 1, 7, Nullable{Any}())
|
||
|
||
julia> fetch(a)+fetch(b)
|
||
100001564</code></pre><p>This example demonstrates a powerful and often-used parallel programming pattern. Many iterations run independently over several processes, and then their results are combined using some function. The combination process is called a <em>reduction</em>, since it is generally tensor-rank-reducing: a vector of numbers is reduced to a single number, or a matrix is reduced to a single row or column, etc. In code, this typically looks like the pattern <code>x = f(x,v[i])</code>, where <code>x</code> is the accumulator, <code>f</code> is the reduction function, and the <code>v[i]</code> are the elements being reduced. It is desirable for <code>f</code> to be associative, so that it does not matter what order the operations are performed in.</p><p>Notice that our use of this pattern with <code>count_heads</code> can be generalized. We used two explicit <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a> statements, which limits the parallelism to two processes. To run on any number of processes, we can use a <em>parallel for loop</em>, which can be written in Julia using <a href="../stdlib/parallel.html#Base.Distributed.@parallel"><code>@parallel</code></a> like this:</p><pre><code class="language-julia">nheads = @parallel (+) for i = 1:200000000
|
||
Int(rand(Bool))
|
||
end</code></pre><p>This construct implements the pattern of assigning iterations to multiple processes, and combining them with a specified reduction (in this case <code>(+)</code>). The result of each iteration is taken as the value of the last expression inside the loop. The whole parallel loop expression itself evaluates to the final answer.</p><p>Note that although parallel for loops look like serial for loops, their behavior is dramatically different. In particular, the iterations do not happen in a specified order, and writes to variables or arrays will not be globally visible since iterations run on different processes. Any variables used inside the parallel loop will be copied and broadcast to each process.</p><p>For example, the following code will not work as intended:</p><pre><code class="language-julia">a = zeros(100000)
|
||
@parallel for i = 1:100000
|
||
a[i] = i
|
||
end</code></pre><p>This code will not initialize all of <code>a</code>, since each process will have a separate copy of it. Parallel for loops like these must be avoided. Fortunately, <a href="parallel-computing.html#man-shared-arrays-1">Shared Arrays</a> can be used to get around this limitation:</p><pre><code class="language-julia">a = SharedArray{Float64}(10)
|
||
@parallel for i = 1:10
|
||
a[i] = i
|
||
end</code></pre><p>Using "outside" variables in parallel loops is perfectly reasonable if the variables are read-only:</p><pre><code class="language-julia">a = randn(1000)
|
||
@parallel (+) for i = 1:100000
|
||
f(a[rand(1:end)])
|
||
end</code></pre><p>Here each iteration applies <code>f</code> to a randomly-chosen sample from a vector <code>a</code> shared by all processes.</p><p>As you could see, the reduction operator can be omitted if it is not needed. In that case, the loop executes asynchronously, i.e. it spawns independent tasks on all available workers and returns an array of <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> immediately without waiting for completion. The caller can wait for the <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> completions at a later point by calling <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a> on them, or wait for completion at the end of the loop by prefixing it with <a href="../stdlib/parallel.html#Base.@sync"><code>@sync</code></a>, like <code>@sync @parallel for</code>.</p><p>In some cases no reduction operator is needed, and we merely wish to apply a function to all integers in some range (or, more generally, to all elements in some collection). This is another useful operation called <em>parallel map</em>, implemented in Julia as the <a href="../stdlib/parallel.html#Base.Distributed.pmap"><code>pmap()</code></a> function. For example, we could compute the singular values of several large random matrices in parallel as follows:</p><pre><code class="language-julia-repl">julia> M = Matrix{Float64}[rand(1000,1000) for i = 1:10];
|
||
|
||
julia> pmap(svd, M);</code></pre><p>Julia's <a href="../stdlib/parallel.html#Base.Distributed.pmap"><code>pmap()</code></a> is designed for the case where each function call does a large amount of work. In contrast, <code>@parallel for</code> can handle situations where each iteration is tiny, perhaps merely summing two numbers. Only worker processes are used by both <a href="../stdlib/parallel.html#Base.Distributed.pmap"><code>pmap()</code></a> and <code>@parallel for</code> for the parallel computation. In case of <code>@parallel for</code>, the final reduction is done on the calling process.</p><h2><a class="nav-anchor" id="Synchronization-With-Remote-References-1" href="#Synchronization-With-Remote-References-1">Synchronization With Remote References</a></h2><h2><a class="nav-anchor" id="Scheduling-1" href="#Scheduling-1">Scheduling</a></h2><p>Julia's parallel programming platform uses <a href="control-flow.html#man-tasks-1">Tasks (aka Coroutines)</a> to switch among multiple computations. Whenever code performs a communication operation like <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a> or <a href="../stdlib/parallel.html#Base.wait"><code>wait()</code></a>, the current task is suspended and a scheduler picks another task to run. A task is restarted when the event it is waiting for completes.</p><p>For many problems, it is not necessary to think about tasks directly. However, they can be used to wait for multiple events at the same time, which provides for <em>dynamic scheduling</em>. In dynamic scheduling, a program decides what to compute or where to compute it based on when other jobs finish. This is needed for unpredictable or unbalanced workloads, where we want to assign more work to processes only when they finish their current tasks.</p><p>As an example, consider computing the singular values of matrices of different sizes:</p><pre><code class="language-julia-repl">julia> M = Matrix{Float64}[rand(800,800), rand(600,600), rand(800,800), rand(600,600)];
|
||
|
||
julia> pmap(svd, M);</code></pre><p>If one process handles both 800×800 matrices and another handles both 600×600 matrices, we will not get as much scalability as we could. The solution is to make a local task to "feed" work to each process when it completes its current task. For example, consider a simple <a href="../stdlib/parallel.html#Base.Distributed.pmap"><code>pmap()</code></a> implementation:</p><pre><code class="language-julia">function pmap(f, lst)
|
||
np = nprocs() # determine the number of processes available
|
||
n = length(lst)
|
||
results = Vector{Any}(n)
|
||
i = 1
|
||
# function to produce the next work item from the queue.
|
||
# in this case it's just an index.
|
||
nextidx() = (idx=i; i+=1; idx)
|
||
@sync begin
|
||
for p=1:np
|
||
if p != myid() || np == 1
|
||
@async begin
|
||
while true
|
||
idx = nextidx()
|
||
if idx > n
|
||
break
|
||
end
|
||
results[idx] = remotecall_fetch(f, p, lst[idx])
|
||
end
|
||
end
|
||
end
|
||
end
|
||
end
|
||
results
|
||
end</code></pre><p><a href="../stdlib/parallel.html#Base.@async"><code>@async</code></a> is similar to <a href="../stdlib/parallel.html#Base.Distributed.@spawn"><code>@spawn</code></a>, but only runs tasks on the local process. We use it to create a "feeder" task for each process. Each task picks the next index that needs to be computed, then waits for its process to finish, then repeats until we run out of indexes. Note that the feeder tasks do not begin to execute until the main task reaches the end of the <a href="../stdlib/parallel.html#Base.@sync"><code>@sync</code></a> block, at which point it surrenders control and waits for all the local tasks to complete before returning from the function. The feeder tasks are able to share state via <code>nextidx()</code> because they all run on the same process. No locking is required, since the threads are scheduled cooperatively and not preemptively. This means context switches only occur at well-defined points: in this case, when <a href="../stdlib/parallel.html#Base.Distributed.remotecall_fetch-Tuple{Any,Integer,Vararg{Any,N} where N}"><code>remotecall_fetch()</code></a> is called.</p><h2><a class="nav-anchor" id="Channels-1" href="#Channels-1">Channels</a></h2><p>The section on <a href="../stdlib/parallel.html#Core.Task"><code>Task</code></a>s in <a href="control-flow.html#Control-Flow-1">Control Flow</a> discussed the execution of multiple functions in a co-operative manner. <a href="../stdlib/parallel.html#Base.Channel"><code>Channel</code></a>s can be quite useful to pass data between running tasks, particularly those involving I/O operations.</p><p>Examples of operations involving I/O include reading/writing to files, accessing web services, executing external programs, etc. In all these cases, overall execution time can be improved if other tasks can be run while a file is being read, or while waiting for an external service/program to complete.</p><p>A channel can be visualized as a pipe, i.e., it has a write end and read end.</p><ul><li><p>Multiple writers in different tasks can write to the same channel concurrently via <a href="../stdlib/parallel.html#Base.put!-Tuple{Channel,Any}"><code>put!()</code></a> calls.</p></li><li><p>Multiple readers in different tasks can read data concurrently via <a href="../stdlib/io-network.html#Base.take!-Tuple{Base.AbstractIOBuffer}"><code>take!()</code></a> calls.</p></li><li><p>As an example:</p><pre><code class="language-julia"># Given Channels c1 and c2,
|
||
c1 = Channel(32)
|
||
c2 = Channel(32)
|
||
|
||
# and a function `foo()` which reads items from from c1, processes the item read
|
||
# and writes a result to c2,
|
||
function foo()
|
||
while true
|
||
data = take!(c1)
|
||
[...] # process data
|
||
put!(c2, result) # write out result
|
||
end
|
||
end
|
||
|
||
# we can schedule `n` instances of `foo()` to be active concurrently.
|
||
for _ in 1:n
|
||
@schedule foo()
|
||
end</code></pre></li><li><p>Channels are created via the <code>Channel{T}(sz)</code> constructor. The channel will only hold objects of type <code>T</code>. If the type is not specified, the channel can hold objects of any type. <code>sz</code> refers to the maximum number of elements that can be held in the channel at any time. For example, <code>Channel(32)</code> creates a channel that can hold a maximum of 32 objects of any type. A <code>Channel{MyType}(64)</code> can hold up to 64 objects of <code>MyType</code> at any time.</p></li><li><p>If a <a href="../stdlib/parallel.html#Base.Channel"><code>Channel</code></a> is empty, readers (on a <a href="../stdlib/io-network.html#Base.take!-Tuple{Base.AbstractIOBuffer}"><code>take!()</code></a> call) will block until data is available.</p></li><li><p>If a <a href="../stdlib/parallel.html#Base.Channel"><code>Channel</code></a> is full, writers (on a <a href="../stdlib/parallel.html#Base.put!-Tuple{Channel,Any}"><code>put!()</code></a> call) will block until space becomes available.</p></li><li><p><a href="../stdlib/parallel.html#Base.isready-Tuple{Channel}"><code>isready()</code></a> tests for the presence of any object in the channel, while <a href="../stdlib/parallel.html#Base.wait"><code>wait()</code></a> waits for an object to become available.</p></li><li><p>A <a href="../stdlib/parallel.html#Base.Channel"><code>Channel</code></a> is in an open state initially. This means that it can be read from and written to freely via <a href="../stdlib/io-network.html#Base.take!-Tuple{Base.AbstractIOBuffer}"><code>take!()</code></a> and <a href="../stdlib/parallel.html#Base.put!-Tuple{Channel,Any}"><code>put!()</code></a> calls. <a href="../stdlib/io-network.html#Base.close"><code>close()</code></a> closes a <a href="../stdlib/parallel.html#Base.Channel"><code>Channel</code></a>. On a closed <a href="../stdlib/parallel.html#Base.Channel"><code>Channel</code></a>, <a href="../stdlib/parallel.html#Base.put!-Tuple{Channel,Any}"><code>put!()</code></a> will fail. For example:</p></li></ul><pre><code class="language-julia-repl">julia> c = Channel(2);
|
||
|
||
julia> put!(c, 1) # `put!` on an open channel succeeds
|
||
1
|
||
|
||
julia> close(c);
|
||
|
||
julia> put!(c, 2) # `put!` on a closed channel throws an exception.
|
||
ERROR: InvalidStateException("Channel is closed.",:closed)
|
||
[...]</code></pre><ul><li><p><a href="../stdlib/io-network.html#Base.take!-Tuple{Base.AbstractIOBuffer}"><code>take!()</code></a> and <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a> (which retrieves but does not remove the value) on a closed channel successfully return any existing values until it is emptied. Continuing the above example:</p></li></ul><pre><code class="language-julia-repl">julia> fetch(c) # Any number of `fetch` calls succeed.
|
||
1
|
||
|
||
julia> fetch(c)
|
||
1
|
||
|
||
julia> take!(c) # The first `take!` removes the value.
|
||
1
|
||
|
||
julia> take!(c) # No more data available on a closed channel.
|
||
ERROR: InvalidStateException("Channel is closed.",:closed)
|
||
[...]</code></pre><p>A <code>Channel</code> can be used as an iterable object in a <code>for</code> loop, in which case the loop runs as long as the <code>Channel</code> has data or is open. The loop variable takes on all values added to the <code>Channel</code>. The <code>for</code> loop is terminated once the <code>Channel</code> is closed and emptied.</p><p>For example, the following would cause the <code>for</code> loop to wait for more data:</p><pre><code class="language-julia-repl">julia> c = Channel{Int}(10);
|
||
|
||
julia> foreach(i->put!(c, i), 1:3) # add a few entries
|
||
|
||
julia> data = [i for i in c]</code></pre><p>while this will return after reading all data:</p><pre><code class="language-julia-repl">julia> c = Channel{Int}(10);
|
||
|
||
julia> foreach(i->put!(c, i), 1:3); # add a few entries
|
||
|
||
julia> close(c); # `for` loops can exit
|
||
|
||
julia> data = [i for i in c]
|
||
3-element Array{Int64,1}:
|
||
1
|
||
2
|
||
3</code></pre><p>Consider a simple example using channels for inter-task communication. We start 4 tasks to process data from a single <code>jobs</code> channel. Jobs, identified by an id (<code>job_id</code>), are written to the channel. Each task in this simulation reads a <code>job_id</code>, waits for a random amout of time and writes back a tuple of <code>job_id</code> and the simulated time to the results channel. Finally all the <code>results</code> are printed out.</p><pre><code class="language-julia-repl">julia> const jobs = Channel{Int}(32);
|
||
|
||
julia> const results = Channel{Tuple}(32);
|
||
|
||
julia> function do_work()
|
||
for job_id in jobs
|
||
exec_time = rand()
|
||
sleep(exec_time) # simulates elapsed time doing actual work
|
||
# typically performed externally.
|
||
put!(results, (job_id, exec_time))
|
||
end
|
||
end;
|
||
|
||
julia> function make_jobs(n)
|
||
for i in 1:n
|
||
put!(jobs, i)
|
||
end
|
||
end;
|
||
|
||
julia> n = 12;
|
||
|
||
julia> @schedule make_jobs(n); # feed the jobs channel with "n" jobs
|
||
|
||
julia> for i in 1:4 # start 4 tasks to process requests in parallel
|
||
@schedule do_work()
|
||
end
|
||
|
||
julia> @elapsed while n > 0 # print out results
|
||
job_id, exec_time = take!(results)
|
||
println("$job_id finished in $(round(exec_time,2)) seconds")
|
||
n = n - 1
|
||
end
|
||
4 finished in 0.22 seconds
|
||
3 finished in 0.45 seconds
|
||
1 finished in 0.5 seconds
|
||
7 finished in 0.14 seconds
|
||
2 finished in 0.78 seconds
|
||
5 finished in 0.9 seconds
|
||
9 finished in 0.36 seconds
|
||
6 finished in 0.87 seconds
|
||
8 finished in 0.79 seconds
|
||
10 finished in 0.64 seconds
|
||
12 finished in 0.5 seconds
|
||
11 finished in 0.97 seconds
|
||
0.029772311</code></pre><p>The current version of Julia multiplexes all tasks onto a single OS thread. Thus, while tasks involving I/O operations benefit from parallel execution, compute bound tasks are effectively executed sequentially on a single OS thread. Future versions of Julia may support scheduling of tasks on multiple threads, in which case compute bound tasks will see benefits of parallel execution too.</p><h2><a class="nav-anchor" id="Remote-References-and-AbstractChannels-1" href="#Remote-References-and-AbstractChannels-1">Remote References and AbstractChannels</a></h2><p>Remote references always refer to an implementation of an <code>AbstractChannel</code>.</p><p>A concrete implementation of an <code>AbstractChannel</code> (like <code>Channel</code>), is required to implement <a href="../stdlib/parallel.html#Base.put!-Tuple{Channel,Any}"><code>put!()</code></a>, <a href="../stdlib/io-network.html#Base.take!-Tuple{Base.AbstractIOBuffer}"><code>take!()</code></a>, <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a>, <a href="../stdlib/parallel.html#Base.isready-Tuple{Channel}"><code>isready()</code></a> and <a href="../stdlib/parallel.html#Base.wait"><code>wait()</code></a>. The remote object referred to by a <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> is stored in a <code>Channel{Any}(1)</code>, i.e., a <code>Channel</code> of size 1 capable of holding objects of <code>Any</code> type.</p><p><a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a>, which is rewritable, can point to any type and size of channels, or any other implementation of an <code>AbstractChannel</code>.</p><p>The constructor <code>RemoteChannel(f::Function, pid)()</code> allows us to construct references to channels holding more than one value of a specific type. <code>f()</code> is a function executed on <code>pid</code> and it must return an <code>AbstractChannel</code>.</p><p>For example, <code>RemoteChannel(()->Channel{Int}(10), pid)</code>, will return a reference to a channel of type <code>Int</code> and size 10. The channel exists on worker <code>pid</code>.</p><p>Methods <a href="../stdlib/parallel.html#Base.put!-Tuple{Channel,Any}"><code>put!()</code></a>, <a href="../stdlib/io-network.html#Base.take!-Tuple{Base.AbstractIOBuffer}"><code>take!()</code></a>, <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a>, <a href="../stdlib/parallel.html#Base.isready-Tuple{Channel}"><code>isready()</code></a> and <a href="../stdlib/parallel.html#Base.wait"><code>wait()</code></a> on a <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> are proxied onto the backing store on the remote process.</p><p><a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> can thus be used to refer to user implemented <code>AbstractChannel</code> objects. A simple example of this is provided in <code>examples/dictchannel.jl</code> which uses a dictionary as its remote store.</p><h2><a class="nav-anchor" id="Channels-and-RemoteChannels-1" href="#Channels-and-RemoteChannels-1">Channels and RemoteChannels</a></h2><ul><li><p>A <a href="../stdlib/parallel.html#Base.Channel"><code>Channel</code></a> is local to a process. Worker 2 cannot directly refer to a <code>Channel</code> on worker 3 and vice-versa. A <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a>, however, can put and take values across workers.</p></li><li><p>A <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> can be thought of as a <em>handle</em> to a <code>Channel</code>.</p></li><li><p>The process id, <code>pid</code>, associated with a <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> identifies the process where the backing store, i.e., the backing <code>Channel</code> exists.</p></li><li><p>Any process with a reference to a <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> can put and take items from the channel. Data is automatically sent to (or retrieved from) the process a <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> is associated with.</p></li><li><p>Serializing a <code>Channel</code> also serializes any data present in the channel. Deserializing it therefore effectively makes a copy of the original object.</p></li><li><p>On the other hand, serializing a <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> only involves the serialization of an identifier that identifies the location and instance of <code>Channel</code> referred to by the handle. A deserialized <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> object (on any worker), therefore also points to the same backing store as the original.</p></li></ul><p>The channels example from above can be modified for interprocess communication, as shown below.</p><p>We start 4 workers to process a single <code>jobs</code> remote channel. Jobs, identified by an id (<code>job_id</code>), are written to the channel. Each remotely executing task in this simulation reads a <code>job_id</code>, waits for a random amount of time and writes back a tuple of <code>job_id</code>, time taken and its own <code>pid</code> to the results channel. Finally all the <code>results</code> are printed out on the master process.</p><pre><code class="language-julia-repl">julia> addprocs(4); # add worker processes
|
||
|
||
julia> const jobs = RemoteChannel(()->Channel{Int}(32));
|
||
|
||
julia> const results = RemoteChannel(()->Channel{Tuple}(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;
|
||
|
||
julia> @schedule make_jobs(n); # feed the jobs channel with "n" jobs
|
||
|
||
julia> for p in workers() # start tasks on the workers to process requests in parallel
|
||
@async 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,2)) seconds on worker $where")
|
||
n = n - 1
|
||
end
|
||
1 finished in 0.18 seconds on worker 4
|
||
2 finished in 0.26 seconds on worker 5
|
||
6 finished in 0.12 seconds on worker 4
|
||
7 finished in 0.18 seconds on worker 4
|
||
5 finished in 0.35 seconds on worker 5
|
||
4 finished in 0.68 seconds on worker 2
|
||
3 finished in 0.73 seconds on worker 3
|
||
11 finished in 0.01 seconds on worker 3
|
||
12 finished in 0.02 seconds on worker 3
|
||
9 finished in 0.26 seconds on worker 5
|
||
8 finished in 0.57 seconds on worker 4
|
||
10 finished in 0.58 seconds on worker 2
|
||
0.055971741</code></pre><h2><a class="nav-anchor" id="Remote-References-and-Distributed-Garbage-Collection-1" href="#Remote-References-and-Distributed-Garbage-Collection-1">Remote References and Distributed Garbage Collection</a></h2><p>Objects referred to by remote references can be freed only when <em>all</em> held references in the cluster are deleted.</p><p>The node where the value is stored keeps track of which of the workers have a reference to it. Every time a <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> or a (unfetched) <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> is serialized to a worker, the node pointed to by the reference is notified. And every time a <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a> or a (unfetched) <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> is garbage collected locally, the node owning the value is again notified.</p><p>The notifications are done via sending of "tracking" messages–an "add reference" message when a reference is serialized to a different process and a "delete reference" message when a reference is locally garbage collected.</p><p>Since <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a>s are write-once and cached locally, the act of <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a>ing a <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> also updates reference tracking information on the node owning the value.</p><p>The node which owns the value frees it once all references to it are cleared.</p><p>With <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a>s, serializing an already fetched <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> to a different node also sends the value since the original remote store may have collected the value by this time.</p><p>It is important to note that <em>when</em> an object is locally garbage collected depends on the size of the object and the current memory pressure in the system.</p><p>In case of remote references, the size of the local reference object is quite small, while the value stored on the remote node may be quite large. Since the local object may not be collected immediately, it is a good practice to explicitly call <a href="../stdlib/base.html#Base.finalize"><code>finalize()</code></a> on local instances of a <a href="../stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}"><code>RemoteChannel</code></a>, or on unfetched <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a>s. Since calling <a href="../stdlib/parallel.html#Base.fetch-Tuple{Channel}"><code>fetch()</code></a> on a <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a> also removes its reference from the remote store, this is not required on fetched <a href="../stdlib/parallel.html#Base.Distributed.Future"><code>Future</code></a>s. Explicitly calling <a href="../stdlib/base.html#Base.finalize"><code>finalize()</code></a> results in an immediate message sent to the remote node to go ahead and remove its reference to the value.</p><p>Once finalized, a reference becomes invalid and cannot be used in any further calls.</p><h2><a class="nav-anchor" id="man-shared-arrays-1" href="#man-shared-arrays-1">Shared Arrays</a></h2><p>Shared Arrays use system shared memory to map the same array across many processes. While there are some similarities to a <a href="https://github.com/JuliaParallel/DistributedArrays.jl"><code>DArray</code></a>, the behavior of a <a href="../stdlib/parallel.html#Base.SharedArray"><code>SharedArray</code></a> is quite different. In a <a href="https://github.com/JuliaParallel/DistributedArrays.jl"><code>DArray</code></a>, each process has local access to just a chunk of the data, and no two processes share the same chunk; in contrast, in a <a href="../stdlib/parallel.html#Base.SharedArray"><code>SharedArray</code></a> each "participating" process has access to the entire array. A <a href="../stdlib/parallel.html#Base.SharedArray"><code>SharedArray</code></a> is a good choice when you want to have a large amount of data jointly accessible to two or more processes on the same machine.</p><p><a href="../stdlib/parallel.html#Base.SharedArray"><code>SharedArray</code></a> indexing (assignment and accessing values) works just as with regular arrays, and is efficient because the underlying memory is available to the local process. Therefore, most algorithms work naturally on <a href="../stdlib/parallel.html#Base.SharedArray"><code>SharedArray</code></a>s, albeit in single-process mode. In cases where an algorithm insists on an <a href="../stdlib/arrays.html#Core.Array"><code>Array</code></a> input, the underlying array can be retrieved from a <a href="../stdlib/parallel.html#Base.SharedArray"><code>SharedArray</code></a> by calling <a href="../stdlib/parallel.html#Base.sdata"><code>sdata()</code></a>. For other <code>AbstractArray</code> types, <a href="../stdlib/parallel.html#Base.sdata"><code>sdata()</code></a> just returns the object itself, so it's safe to use <a href="../stdlib/parallel.html#Base.sdata"><code>sdata()</code></a> on any <code>Array</code>-type object.</p><p>The constructor for a shared array is of the form:</p><pre><code class="language-julia">SharedArray{T,N}(dims::NTuple; init=false, pids=Int[])</code></pre><p>which creates an <code>N</code>-dimensional shared array of a bits type <code>T</code> and size <code>dims</code> across the processes specified by <code>pids</code>. Unlike distributed arrays, a shared array is accessible only from those participating workers specified by the <code>pids</code> named argument (and the creating process too, if it is on the same host).</p><p>If an <code>init</code> function, of signature <code>initfn(S::SharedArray)</code>, is specified, it is called on all the participating workers. You can specify that each worker runs the <code>init</code> function on a distinct portion of the array, thereby parallelizing initialization.</p><p>Here's a brief example:</p><pre><code class="language-julia-repl">julia> addprocs(3)
|
||
3-element Array{Int64,1}:
|
||
2
|
||
3
|
||
4
|
||
|
||
julia> S = SharedArray{Int,2}((3,4), init = S -> S[Base.localindexes(S)] = myid())
|
||
3×4 SharedArray{Int64,2}:
|
||
2 2 3 4
|
||
2 3 3 4
|
||
2 3 4 4
|
||
|
||
julia> S[3,2] = 7
|
||
7
|
||
|
||
julia> S
|
||
3×4 SharedArray{Int64,2}:
|
||
2 2 3 4
|
||
2 3 3 4
|
||
2 7 4 4</code></pre><p><a href="../stdlib/parallel.html#Base.localindexes"><code>Base.localindexes()</code></a> provides disjoint one-dimensional ranges of indexes, and is sometimes convenient for splitting up tasks among processes. You can, of course, divide the work any way you wish:</p><pre><code class="language-julia-repl">julia> S = SharedArray{Int,2}((3,4), init = S -> S[indexpids(S):length(procs(S)):length(S)] = myid())
|
||
3×4 SharedArray{Int64,2}:
|
||
2 2 2 2
|
||
3 3 3 3
|
||
4 4 4 4</code></pre><p>Since all processes have access to the underlying data, you do have to be careful not to set up conflicts. For example:</p><pre><code class="language-julia">@sync begin
|
||
for p in procs(S)
|
||
@async begin
|
||
remotecall_wait(fill!, p, S, p)
|
||
end
|
||
end
|
||
end</code></pre><p>would result in undefined behavior. Because each process fills the <em>entire</em> array with its own <code>pid</code>, whichever process is the last to execute (for any particular element of <code>S</code>) will have its <code>pid</code> retained.</p><p>As a more extended and complex example, consider running the following "kernel" in parallel:</p><pre><code class="language-julia">q[i,j,t+1] = q[i,j,t] + u[i,j,t]</code></pre><p>In this case, if we try to split up the work using a one-dimensional index, we are likely to run into trouble: if <code>q[i,j,t]</code> is near the end of the block assigned to one worker and <code>q[i,j,t+1]</code> is near the beginning of the block assigned to another, it's very likely that <code>q[i,j,t]</code> will not be ready at the time it's needed for computing <code>q[i,j,t+1]</code>. In such cases, one is better off chunking the array manually. Let's split along the second dimension. Define a function that returns the <code>(irange, jrange)</code> indexes assigned to this worker:</p><pre><code class="language-julia-repl">julia> @everywhere function myrange(q::SharedArray)
|
||
idx = indexpids(q)
|
||
if idx == 0 # This worker is not assigned a piece
|
||
return 1:0, 1:0
|
||
end
|
||
nchunks = length(procs(q))
|
||
splits = [round(Int, s) for s in linspace(0,size(q,2),nchunks+1)]
|
||
1:size(q,1), splits[idx]+1:splits[idx+1]
|
||
end</code></pre><p>Next, define the kernel:</p><pre><code class="language-julia-repl">julia> @everywhere function advection_chunk!(q, u, irange, jrange, trange)
|
||
@show (irange, jrange, trange) # display so we can see what's happening
|
||
for t in trange, j in jrange, i in irange
|
||
q[i,j,t+1] = q[i,j,t] + u[i,j,t]
|
||
end
|
||
q
|
||
end</code></pre><p>We also define a convenience wrapper for a <code>SharedArray</code> implementation</p><pre><code class="language-julia-repl">julia> @everywhere advection_shared_chunk!(q, u) =
|
||
advection_chunk!(q, u, myrange(q)..., 1:size(q,3)-1)</code></pre><p>Now let's compare three different versions, one that runs in a single process:</p><pre><code class="language-julia-repl">julia> advection_serial!(q, u) = advection_chunk!(q, u, 1:size(q,1), 1:size(q,2), 1:size(q,3)-1);</code></pre><p>one that uses <a href="../stdlib/parallel.html#Base.Distributed.@parallel"><code>@parallel</code></a>:</p><pre><code class="language-julia-repl">julia> function advection_parallel!(q, u)
|
||
for t = 1:size(q,3)-1
|
||
@sync @parallel for j = 1:size(q,2)
|
||
for i = 1:size(q,1)
|
||
q[i,j,t+1]= q[i,j,t] + u[i,j,t]
|
||
end
|
||
end
|
||
end
|
||
q
|
||
end;</code></pre><p>and one that delegates in chunks:</p><pre><code class="language-julia-repl">julia> function advection_shared!(q, u)
|
||
@sync begin
|
||
for p in procs(q)
|
||
@async remotecall_wait(advection_shared_chunk!, p, q, u)
|
||
end
|
||
end
|
||
q
|
||
end;</code></pre><p>If we create <code>SharedArray</code>s and time these functions, we get the following results (with <code>julia -p 4</code>):</p><pre><code class="language-julia-repl">julia> q = SharedArray{Float64,3}((500,500,500));
|
||
|
||
julia> u = SharedArray{Float64,3}((500,500,500));</code></pre><p>Run the functions once to JIT-compile and <a href="../stdlib/base.html#Base.@time"><code>@time</code></a> them on the second run:</p><pre><code class="language-julia-repl">julia> @time advection_serial!(q, u);
|
||
(irange,jrange,trange) = (1:500,1:500,1:499)
|
||
830.220 milliseconds (216 allocations: 13820 bytes)
|
||
|
||
julia> @time advection_parallel!(q, u);
|
||
2.495 seconds (3999 k allocations: 289 MB, 2.09% gc time)
|
||
|
||
julia> @time advection_shared!(q,u);
|
||
From worker 2: (irange,jrange,trange) = (1:500,1:125,1:499)
|
||
From worker 4: (irange,jrange,trange) = (1:500,251:375,1:499)
|
||
From worker 3: (irange,jrange,trange) = (1:500,126:250,1:499)
|
||
From worker 5: (irange,jrange,trange) = (1:500,376:500,1:499)
|
||
238.119 milliseconds (2264 allocations: 169 KB)</code></pre><p>The biggest advantage of <code>advection_shared!</code> is that it minimizes traffic among the workers, allowing each to compute for an extended time on the assigned piece.</p><h2><a class="nav-anchor" id="Shared-Arrays-and-Distributed-Garbage-Collection-1" href="#Shared-Arrays-and-Distributed-Garbage-Collection-1">Shared Arrays and Distributed Garbage Collection</a></h2><p>Like remote references, shared arrays are also dependent on garbage collection on the creating node to release references from all participating workers. Code which creates many short lived shared array objects would benefit from explicitly finalizing these objects as soon as possible. This results in both memory and file handles mapping the shared segment being released sooner.</p><h2><a class="nav-anchor" id="ClusterManagers-1" href="#ClusterManagers-1">ClusterManagers</a></h2><p>The launching, management and networking of Julia processes into a logical cluster is done via cluster managers. A <code>ClusterManager</code> is responsible for</p><ul><li><p>launching worker processes in a cluster environment</p></li><li><p>managing events during the lifetime of each worker</p></li><li><p>optionally, providing data transport</p></li></ul><p>A Julia cluster has the following characteristics:</p><ul><li><p>The initial Julia process, also called the <code>master</code>, is special and has an <code>id</code> of 1.</p></li><li><p>Only the <code>master</code> process can add or remove worker processes.</p></li><li><p>All processes can directly communicate with each other.</p></li></ul><p>Connections between workers (using the in-built TCP/IP transport) is established in the following manner:</p><ul><li><p><a href="../stdlib/parallel.html#Base.Distributed.addprocs"><code>addprocs()</code></a> is called on the master process with a <code>ClusterManager</code> object.</p></li><li><p><a href="../stdlib/parallel.html#Base.Distributed.addprocs"><code>addprocs()</code></a> calls the appropriate <a href="../stdlib/parallel.html#Base.Distributed.launch"><code>launch()</code></a> method which spawns required number of worker processes on appropriate machines.</p></li><li><p>Each worker starts listening on a free port and writes out its host and port information to <a href="../stdlib/io-network.html#Base.STDOUT"><code>STDOUT</code></a>.</p></li><li><p>The cluster manager captures the <a href="../stdlib/io-network.html#Base.STDOUT"><code>STDOUT</code></a> of each worker and makes it available to the master process.</p></li><li><p>The master process parses this information and sets up TCP/IP connections to each worker.</p></li><li><p>Every worker is also notified of other workers in the cluster.</p></li><li><p>Each worker connects to all workers whose <code>id</code> is less than the worker's own <code>id</code>.</p></li><li><p>In this way a mesh network is established, wherein every worker is directly connected with every other worker.</p></li></ul><p>While the default transport layer uses plain <code>TCPSocket</code>, it is possible for a Julia cluster to provide its own transport.</p><p>Julia provides two in-built cluster managers:</p><ul><li><p><code>LocalManager</code>, used when <a href="../stdlib/parallel.html#Base.Distributed.addprocs"><code>addprocs()</code></a> or <a href="../stdlib/parallel.html#Base.Distributed.addprocs"><code>addprocs(np::Integer)</code></a> are called</p></li><li><p><code>SSHManager</code>, used when <a href="../stdlib/parallel.html#Base.Distributed.addprocs"><code>addprocs(hostnames::Array)</code></a> is called with a list of hostnames</p></li></ul><p><code>LocalManager</code> is used to launch additional workers on the same host, thereby leveraging multi-core and multi-processor hardware.</p><p>Thus, a minimal cluster manager would need to:</p><ul><li><p>be a subtype of the abstract <code>ClusterManager</code></p></li><li><p>implement <a href="../stdlib/parallel.html#Base.Distributed.launch"><code>launch()</code></a>, a method responsible for launching new workers</p></li><li><p>implement <a href="../stdlib/parallel.html#Base.Distributed.manage"><code>manage()</code></a>, which is called at various events during a worker's lifetime (for example, sending an interrupt signal)</p></li></ul><p><a href="../stdlib/parallel.html#Base.Distributed.addprocs"><code>addprocs(manager::FooManager)</code></a> requires <code>FooManager</code> to implement:</p><pre><code class="language-julia">function launch(manager::FooManager, params::Dict, launched::Array, c::Condition)
|
||
[...]
|
||
end
|
||
|
||
function manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol)
|
||
[...]
|
||
end</code></pre><p>As an example let us see how the <code>LocalManager</code>, the manager responsible for starting workers on the same host, is implemented:</p><pre><code class="language-julia">struct LocalManager <: ClusterManager
|
||
np::Integer
|
||
end
|
||
|
||
function launch(manager::LocalManager, params::Dict, launched::Array, c::Condition)
|
||
[...]
|
||
end
|
||
|
||
function manage(manager::LocalManager, id::Integer, config::WorkerConfig, op::Symbol)
|
||
[...]
|
||
end</code></pre><p>The <a href="../stdlib/parallel.html#Base.Distributed.launch"><code>launch()</code></a> method takes the following arguments:</p><ul><li><p><code>manager::ClusterManager</code>: the cluster manager that <a href="../stdlib/parallel.html#Base.Distributed.addprocs"><code>addprocs()</code></a> is called with</p></li><li><p><code>params::Dict</code>: all the keyword arguments passed to <a href="../stdlib/parallel.html#Base.Distributed.addprocs"><code>addprocs()</code></a></p></li><li><p><code>launched::Array</code>: the array to append one or more <code>WorkerConfig</code> objects to</p></li><li><p><code>c::Condition</code>: the condition variable to be notified as and when workers are launched</p></li></ul><p>The <a href="../stdlib/parallel.html#Base.Distributed.launch"><code>launch()</code></a> method is called asynchronously in a separate task. The termination of this task signals that all requested workers have been launched. Hence the <a href="../stdlib/parallel.html#Base.Distributed.launch"><code>launch()</code></a> function MUST exit as soon as all the requested workers have been launched.</p><p>Newly launched workers are connected to each other, and the master process, in an all-to-all manner. Specifying the command argument <code>--worker <cookie></code> results in the launched processes initializing themselves as workers and connections being set up via TCP/IP sockets. Optionally, <code>--bind-to bind_addr[:port]</code> may also be specified to enable other workers to connect to it at the specified <code>bind_addr</code> and <code>port</code>. This is useful for multi-homed hosts.</p><p>As an example of a non-TCP/IP transport, an implementation may choose to use MPI, in which case <code>--worker</code> must NOT be specified. Instead, newly launched workers should call <code>init_worker(cookie)</code> before using any of the parallel constructs.</p><p>For every worker launched, the <a href="../stdlib/parallel.html#Base.Distributed.launch"><code>launch()</code></a> method must add a <code>WorkerConfig</code> object (with appropriate fields initialized) to <code>launched</code></p><pre><code class="language-julia">mutable struct WorkerConfig
|
||
# Common fields relevant to all cluster managers
|
||
io::Nullable{IO}
|
||
host::Nullable{AbstractString}
|
||
port::Nullable{Integer}
|
||
|
||
# Used when launching additional workers at a host
|
||
count::Nullable{Union{Int, Symbol}}
|
||
exename::Nullable{AbstractString}
|
||
exeflags::Nullable{Cmd}
|
||
|
||
# External cluster managers can use this to store information at a per-worker level
|
||
# Can be a dict if multiple fields need to be stored.
|
||
userdata::Nullable{Any}
|
||
|
||
# SSHManager / SSH tunnel connections to workers
|
||
tunnel::Nullable{Bool}
|
||
bind_addr::Nullable{AbstractString}
|
||
sshflags::Nullable{Cmd}
|
||
max_parallel::Nullable{Integer}
|
||
|
||
connect_at::Nullable{Any}
|
||
|
||
[...]
|
||
end</code></pre><p>Most of the fields in <code>WorkerConfig</code> are used by the inbuilt managers. Custom cluster managers would typically specify only <code>io</code> or <code>host</code> / <code>port</code>:</p><ul><li><p>If <code>io</code> is specified, it is used to read host/port information. A Julia worker prints out its bind address and port at startup. This allows Julia workers to listen on any free port available instead of requiring worker ports to be configured manually.</p></li><li><p>If <code>io</code> is not specified, <code>host</code> and <code>port</code> are used to connect.</p></li><li><p><code>count</code>, <code>exename</code> and <code>exeflags</code> are relevant for launching additional workers from a worker. For example, a cluster manager may launch a single worker per node, and use that to launch additional workers.</p><ul><li><p><code>count</code> with an integer value <code>n</code> will launch a total of <code>n</code> workers.</p></li><li><p><code>count</code> with a value of <code>:auto</code> will launch as many workers as the number of cores on that machine.</p></li><li><p><code>exename</code> is the name of the <code>julia</code> executable including the full path.</p></li><li><p><code>exeflags</code> should be set to the required command line arguments for new workers.</p></li></ul></li><li><p><code>tunnel</code>, <code>bind_addr</code>, <code>sshflags</code> and <code>max_parallel</code> are used when a ssh tunnel is required to connect to the workers from the master process.</p></li><li><p><code>userdata</code> is provided for custom cluster managers to store their own worker-specific information.</p></li></ul><p><code>manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol)</code> is called at different times during the worker's lifetime with appropriate <code>op</code> values:</p><ul><li><p>with <code>:register</code>/<code>:deregister</code> when a worker is added / removed from the Julia worker pool.</p></li><li><p>with <code>:interrupt</code> when <code>interrupt(workers)</code> is called. The <code>ClusterManager</code> should signal the appropriate worker with an interrupt signal.</p></li><li><p>with <code>:finalize</code> for cleanup purposes.</p></li></ul><h2><a class="nav-anchor" id="Cluster-Managers-with-Custom-Transports-1" href="#Cluster-Managers-with-Custom-Transports-1">Cluster Managers with Custom Transports</a></h2><p>Replacing the default TCP/IP all-to-all socket connections with a custom transport layer is a little more involved. Each Julia process has as many communication tasks as the workers it is connected to. For example, consider a Julia cluster of 32 processes in an all-to-all mesh network:</p><ul><li><p>Each Julia process thus has 31 communication tasks.</p></li><li><p>Each task handles all incoming messages from a single remote worker in a message-processing loop.</p></li><li><p>The message-processing loop waits on an <code>IO</code> object (for example, a <code>TCPSocket</code> in the default implementation), reads an entire message, processes it and waits for the next one.</p></li><li><p>Sending messages to a process is done directly from any Julia task–not just communication tasks–again, via the appropriate <code>IO</code> object.</p></li></ul><p>Replacing the default transport requires the new implementation to set up connections to remote workers and to provide appropriate <code>IO</code> objects that the message-processing loops can wait on. The manager-specific callbacks to be implemented are:</p><pre><code class="language-julia">connect(manager::FooManager, pid::Integer, config::WorkerConfig)
|
||
kill(manager::FooManager, pid::Int, config::WorkerConfig)</code></pre><p>The default implementation (which uses TCP/IP sockets) is implemented as <code>connect(manager::ClusterManager, pid::Integer, config::WorkerConfig)</code>.</p><p><code>connect</code> should return a pair of <code>IO</code> objects, one for reading data sent from worker <code>pid</code>, and the other to write data that needs to be sent to worker <code>pid</code>. Custom cluster managers can use an in-memory <code>BufferStream</code> as the plumbing to proxy data between the custom, possibly non-<code>IO</code> transport and Julia's in-built parallel infrastructure.</p><p>A <code>BufferStream</code> is an in-memory <code>IOBuffer</code> which behaves like an <code>IO</code>–it is a stream which can be handled asynchronously.</p><p>Folder <code>examples/clustermanager/0mq</code> contains an example of using ZeroMQ to connect Julia workers in a star topology with a 0MQ broker in the middle. Note: The Julia processes are still all <em>logically</em> connected to each other–any worker can message any other worker directly without any awareness of 0MQ being used as the transport layer.</p><p>When using custom transports:</p><ul><li><p>Julia workers must NOT be started with <code>--worker</code>. Starting with <code>--worker</code> will result in the newly launched workers defaulting to the TCP/IP socket transport implementation.</p></li><li><p>For every incoming logical connection with a worker, <code>Base.process_messages(rd::IO, wr::IO)()</code> must be called. This launches a new task that handles reading and writing of messages from/to the worker represented by the <code>IO</code> objects.</p></li><li><p><code>init_worker(cookie, manager::FooManager)</code> MUST be called as part of worker process initialization.</p></li><li><p>Field <code>connect_at::Any</code> in <code>WorkerConfig</code> can be set by the cluster manager when <a href="../stdlib/parallel.html#Base.Distributed.launch"><code>launch()</code></a> is called. The value of this field is passed in in all <a href="../stdlib/io-network.html#Base.connect-Tuple{TCPSocket,Integer}"><code>connect()</code></a> callbacks. Typically, it carries information on <em>how to connect</em> to a worker. For example, the TCP/IP socket transport uses this field to specify the <code>(host, port)</code> tuple at which to connect to a worker.</p></li></ul><p><code>kill(manager, pid, config)</code> is called to remove a worker from the cluster. On the master process, the corresponding <code>IO</code> objects must be closed by the implementation to ensure proper cleanup. The default implementation simply executes an <code>exit()</code> call on the specified remote worker.</p><p><code>examples/clustermanager/simple</code> is an example that shows a simple implementation using UNIX domain sockets for cluster setup.</p><h2><a class="nav-anchor" id="Network-Requirements-for-LocalManager-and-SSHManager-1" href="#Network-Requirements-for-LocalManager-and-SSHManager-1">Network Requirements for LocalManager and SSHManager</a></h2><p>Julia clusters are designed to be executed on already secured environments on infrastructure such as local laptops, departmental clusters, or even the cloud. This section covers network security requirements for the inbuilt <code>LocalManager</code> and <code>SSHManager</code>:</p><ul><li><p>The master process does not listen on any port. It only connects out to the workers.</p></li><li><p>Each worker binds to only one of the local interfaces and listens on the first free port starting from <code>9009</code>.</p></li><li><p><code>LocalManager</code>, used by <code>addprocs(N)</code>, by default binds only to the loopback interface. This means that workers started later on remote hosts (or by anyone with malicious intentions) are unable to connect to the cluster. An <code>addprocs(4)</code> followed by an <code>addprocs(["remote_host"])</code> will fail. Some users may need to create a cluster comprising their local system and a few remote systems. This can be done by explicitly requesting <code>LocalManager</code> to bind to an external network interface via the <code>restrict</code> keyword argument: <code>addprocs(4; restrict=false)</code>.</p></li><li><p><code>SSHManager</code>, used by <code>addprocs(list_of_remote_hosts)</code>, launches workers on remote hosts via SSH. By default SSH is only used to launch Julia workers. Subsequent master-worker and worker-worker connections use plain, unencrypted TCP/IP sockets. The remote hosts must have passwordless login enabled. Additional SSH flags or credentials may be specified via keyword argument <code>sshflags</code>.</p></li><li><p><code>addprocs(list_of_remote_hosts; tunnel=true, sshflags=<ssh keys and other flags>)</code> is useful when we wish to use SSH connections for master-worker too. A typical scenario for this is a local laptop running the Julia REPL (i.e., the master) with the rest of the cluster on the cloud, say on Amazon EC2. In this case only port 22 needs to be opened at the remote cluster coupled with SSH client authenticated via public key infrastructure (PKI). Authentication credentials can be supplied via <code>sshflags</code>, for example <code>sshflags=`-e <keyfile>`</code>.</p><p>Note that worker-worker connections are still plain TCP and the local security policy on the remote cluster must allow for free connections between worker nodes, at least for ports 9009 and above.</p><p>Securing and encrypting all worker-worker traffic (via SSH) or encrypting individual messages can be done via a custom ClusterManager.</p></li></ul><h2><a class="nav-anchor" id="Cluster-Cookie-1" href="#Cluster-Cookie-1">Cluster Cookie</a></h2><p>All processes in a cluster share the same cookie which, by default, is a randomly generated string on the master process:</p><ul><li><p><a href="../stdlib/parallel.html#Base.Distributed.cluster_cookie-Tuple{}"><code>Base.cluster_cookie()</code></a> returns the cookie, while <code>Base.cluster_cookie(cookie)()</code> sets it and returns the new cookie.</p></li><li><p>All connections are authenticated on both sides to ensure that only workers started by the master are allowed to connect to each other.</p></li><li><p>The cookie must be passed to the workers at startup via argument <code>--worker <cookie></code>. Custom ClusterManagers can retrieve the cookie on the master by calling <a href="../stdlib/parallel.html#Base.Distributed.cluster_cookie-Tuple{}"><code>Base.cluster_cookie()</code></a>. Cluster managers not using the default TCP/IP transport (and hence not specifying <code>--worker</code>) must call <code>init_worker(cookie, manager)</code> with the same cookie as on the master.</p></li></ul><p>Note that environments requiring higher levels of security can implement this via a custom <code>ClusterManager</code>. For example, cookies can be pre-shared and hence not specified as a startup argument.</p><h2><a class="nav-anchor" id="Specifying-Network-Topology-(Experimental)-1" href="#Specifying-Network-Topology-(Experimental)-1">Specifying Network Topology (Experimental)</a></h2><p>The keyword argument <code>topology</code> passed to <code>addprocs</code> is used to specify how the workers must be connected to each other:</p><ul><li><p><code>:all_to_all</code>, the default: all workers are connected to each other.</p></li><li><p><code>:master_slave</code>: only the driver process, i.e. <code>pid</code> 1, has connections to the workers.</p></li><li><p><code>:custom</code>: the <code>launch</code> method of the cluster manager specifies the connection topology via the fields <code>ident</code> and <code>connect_idents</code> in <code>WorkerConfig</code>. A worker with a cluster-manager-provided identity <code>ident</code> will connect to all workers specified in <code>connect_idents</code>.</p></li></ul><p>Currently, sending a message between unconnected workers results in an error. This behaviour, as with the functionality and interface, should be considered experimental in nature and may change in future releases.</p><h2><a class="nav-anchor" id="Multi-Threading-(Experimental)-1" href="#Multi-Threading-(Experimental)-1">Multi-Threading (Experimental)</a></h2><p>In addition to tasks, remote calls, and remote references, Julia from <code>v0.5</code> forwards will natively support multi-threading. Note that this section is experimental and the interfaces may change in the future.</p><h3><a class="nav-anchor" id="Setup-1" href="#Setup-1">Setup</a></h3><p>By default, Julia starts up with a single thread of execution. This can be verified by using the command <a href="../stdlib/parallel.html#Base.Threads.nthreads"><code>Threads.nthreads()</code></a>:</p><pre><code class="language-julia-repl">julia> Threads.nthreads()
|
||
1</code></pre><p>The number of threads Julia starts up with is controlled by an environment variable called <code>JULIA_NUM_THREADS</code>. Now, let's start up Julia with 4 threads:</p><pre><code class="language-bash">export JULIA_NUM_THREADS=4</code></pre><p>(The above command works on bourne shells on Linux and OSX. Note that if you're using a C shell on these platforms, you should use the keyword <code>set</code> instead of <code>export</code>. If you're on Windows, start up the command line in the location of <code>julia.exe</code> and use <code>set</code> instead of <code>export</code>.)</p><p>Let's verify there are 4 threads at our disposal.</p><pre><code class="language-julia-repl">julia> Threads.nthreads()
|
||
4</code></pre><p>But we are currently on the master thread. To check, we use the command <a href="../stdlib/parallel.html#Base.Threads.threadid"><code>Threads.threadid()</code></a></p><pre><code class="language-julia-repl">julia> Threads.threadid()
|
||
1</code></pre><h3><a class="nav-anchor" id="The-@threads-Macro-1" href="#The-@threads-Macro-1">The <code>@threads</code> Macro</a></h3><p>Let's work a simple example using our native threads. Let us create an array of zeros:</p><pre><code class="language-julia-repl">julia> a = zeros(10)
|
||
10-element Array{Float64,1}:
|
||
0.0
|
||
0.0
|
||
0.0
|
||
0.0
|
||
0.0
|
||
0.0
|
||
0.0
|
||
0.0
|
||
0.0
|
||
0.0</code></pre><p>Let us operate on this array simultaneously using 4 threads. We'll have each thread write its thread ID into each location.</p><p>Julia supports parallel loops using the <a href="../stdlib/parallel.html#Base.Threads.@threads"><code>Threads.@threads</code></a> macro. This macro is affixed in front of a <code>for</code> loop to indicate to Julia that the loop is a multi-threaded region:</p><pre><code class="language-julia-repl">julia> Threads.@threads for i = 1:10
|
||
a[i] = Threads.threadid()
|
||
end</code></pre><p>The iteration space is split amongst the threads, after which each thread writes its thread ID to its assigned locations:</p><pre><code class="language-julia-repl">julia> a
|
||
10-element Array{Float64,1}:
|
||
1.0
|
||
1.0
|
||
1.0
|
||
2.0
|
||
2.0
|
||
2.0
|
||
3.0
|
||
3.0
|
||
4.0
|
||
4.0</code></pre><p>Note that <a href="../stdlib/parallel.html#Base.Threads.@threads"><code>Threads.@threads</code></a> does not have an optional reduction parameter like <a href="../stdlib/parallel.html#Base.Distributed.@parallel"><code>@parallel</code></a>.</p><h2><a class="nav-anchor" id="@threadcall-(Experimental)-1" href="#@threadcall-(Experimental)-1">@threadcall (Experimental)</a></h2><p>All I/O tasks, timers, REPL commands, etc are multiplexed onto a single OS thread via an event loop. A patched version of libuv (<a href="http://docs.libuv.org/en/v1.x/">http://docs.libuv.org/en/v1.x/</a>) provides this functionality. Yield points provide for co-operatively scheduling multiple tasks onto the same OS thread. I/O tasks and timers yield implicitly while waiting for the event to occur. Calling <a href="../stdlib/parallel.html#Base.yield"><code>yield()</code></a> explicitly allows for other tasks to be scheduled.</p><p>Thus, a task executing a <a href="../stdlib/c.html#ccall"><code>ccall</code></a> effectively prevents the Julia scheduler from executing any other tasks till the call returns. This is true for all calls into external libraries. Exceptions are calls into custom C code that call back into Julia (which may then yield) or C code that calls <code>jl_yield()</code> (C equivalent of <a href="../stdlib/parallel.html#Base.yield"><code>yield()</code></a>).</p><p>Note that while Julia code runs on a single thread (by default), libraries used by Julia may launch their own internal threads. For example, the BLAS library may start as many threads as there are cores on a machine.</p><p>The <code>@threadcall</code> macro addresses scenarios where we do not want a <code>ccall</code> to block the main Julia event loop. It schedules a C function for execution in a separate thread. A threadpool with a default size of 4 is used for this. The size of the threadpool is controlled via environment variable <code>UV_THREADPOOL_SIZE</code>. While waiting for a free thread, and during function execution once a thread is available, the requesting task (on the main Julia event loop) yields to other tasks. Note that <code>@threadcall</code> does not return till the execution is complete. From a user point of view, it is therefore a blocking call like other Julia APIs.</p><p>It is very important that the called function does not call back into Julia.</p><p><code>@threadcall</code> may be removed/changed in future versions of Julia.</p><div class="footnote" id="footnote-1"><a href="#footnote-1"><strong>[1]</strong></a><p>In this context, MPI refers to the MPI-1 standard. Beginning with MPI-2, the MPI standards committee introduced a new set of communication mechanisms, collectively referred to as Remote Memory Access (RMA). The motivation for adding RMA to the MPI standard was to facilitate one-sided communication patterns. For additional information on the latest MPI standard, see <a href="http://mpi-forum.org/docs/">http://mpi-forum.org/docs</a>.</p></div><footer><hr/><a class="previous" href="networking-and-streams.html"><span class="direction">Previous</span><span class="title">Networking and Streams</span></a><a class="next" href="dates.html"><span class="direction">Next</span><span class="title">Date and DateTime</span></a></footer></article></body></html>
|