Tasks and Parallel Computing¶
Tasks¶
Task(func)¶Create a
Task(i.e. coroutine) to execute the given function (which must be callable with no arguments). The task exits when this function returns.
yieldto(task, arg = nothing)¶Switch to the given task. The first time a task is switched to, the task’s function is called with no arguments. On subsequent switches,
argis returned from the task’s last call toyieldto. This is a low-level call that only switches tasks, not considering states or scheduling in any way. Its use is discouraged.
istaskdone(task) → Bool¶Determine whether a task has exited.
istaskstarted(task) → Bool¶Determine whether a task has started executing.
consume(task, values...)¶Receive the next value passed to
produceby the specified task. Additional arguments may be passed, to be returned from the lastproducecall in the producer.
produce(value)¶Send the given value to the last
consumecall, switching to the consumer task. If the nextconsumecall passes any values, they are returned byproduce.
yield()¶Switch to the scheduler to allow another scheduled task to run. A task that calls this function is still runnable, and will be restarted immediately if there are no other runnable tasks.
task_local_storage(key)¶Look up the value of a key in the current task’s task-local storage.
task_local_storage(key, value)Assign a value to a key in the current task’s task-local storage.
task_local_storage(body, key, value)Call the function
bodywith a modified task-local storage, in whichvalueis assigned tokey; the previous value ofkey, or lack thereof, is restored afterwards. Useful for emulating dynamic scoping.
Condition()¶Create an edge-triggered event source that tasks can wait for. Tasks that call
waiton aConditionare suspended and queued. Tasks are woken up whennotifyis later called on theCondition. Edge triggering means that only tasks waiting at the timenotifyis called can be woken up. For level-triggered notifications, you must keep extra state to keep track of whether a notification has happened. TheChanneltype does this, and so can be used for level-triggered events.
notify(condition, val=nothing; all=true, error=false)¶Wake up tasks waiting for a condition, passing them
val. Ifallistrue(the default), all waiting tasks are woken, otherwise only one is. Iferroristrue, the passed value is raised as an exception in the woken tasks.
schedule(t::Task, [val]; error=false)¶Add a task to the scheduler’s queue. This causes the task to run constantly when the system is otherwise idle, unless the task performs a blocking operation such as
wait.If a second argument
valis provided, it will be passed to the task (via the return value ofyieldto) when it runs again. Iferroristrue, the value is raised as an exception in the woken task.
@schedule()¶Wrap an expression in a
Taskand add it to the local machine’s scheduler queue.
@task()¶Wrap an expression in a
Taskwithout executing it, and return theTask. This only creates a task, and does not run it.
sleep(seconds)¶Block the current task for a specified number of seconds. The minimum sleep time is 1 millisecond or input of
0.001.
Channel{T}(sz::Int)¶Constructs a
Channelthat can hold a maximum ofszobjects of typeT.put!calls on a full channel block till an object is removed withtake!.Other constructors:
Channel()- equivalent toChannel{Any}(32)Channel(sz::Int)equivalent toChannel{Any}(sz)
General Parallel Computing Support¶
addprocs(np::Integer; restrict=true, kwargs...) → List of process identifiers¶Launches workers using the in-built
LocalManagerwhich only launches workers on the local host. This can be used to take advantage of multiple cores.addprocs(4)will add 4 processes on the local machine. Ifrestrictistrue, binding is restricted to127.0.0.1.
addprocs(; kwargs...) → List of process identifiersEquivalent to
addprocs(Sys.CPU_CORES;kwargs...)Note that workers do not run a
.juliarc.jlstartup 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.
addprocs(machines; tunnel=false, sshflags=``, max_parallel=10, kwargs...) → List of process identifiersAdd processes on remote machines via SSH. Requires
juliato be installed in the same location on each node, or to be available via a shared file system.machinesis a vector of machine specifications. Workers are started for each specification.A machine specification is either a string
machine_specor a tuple -(machine_spec,count).machine_specis a string of the form[user@]host[:port][bind_addr[:port]].userdefaults to current user,portto the standard ssh port. If[bind_addr[:port]]is specified, other workers will connect to this worker at the specifiedbind_addrandport.countis the number of workers to be launched on the specified host. If specified as:autoit will launch as many workers as the number of cores on the specific host.Keyword arguments:
tunnel: iftruethen SSH tunneling will be used to connect to the worker from the master process. Default isfalse.sshflags: specifies additional ssh options, e.g.sshflags=`-i/home/foo/bar.pem`max_parallel: specifies the maximum number of workers connected to in parallel at a host. Defaults to 10.dir: specifies the working directory on the workers. Defaults to the host’s current directory (as found bypwd())exename: name of thejuliaexecutable. Defaults to"$JULIA_HOME/julia"or"$JULIA_HOME/julia-debug"as the case may be.exeflags: additional flags passed to the worker processes.topology: Specifies how the workers connect to each other. Sending a message between unconnected workers results in an error.topology=:all_to_all: All processes are connected to each other. This is the default.topology=:master_slave: Only the driver process, i.e.pid1 connects to the workers. The workers do not connect to each other.topology=:custom: Thelaunchmethod of the cluster manager specifies the connection topology via fieldsidentandconnect_identsinWorkerConfig. A worker with a cluster manager identityidentwill connect to all workers specified inconnect_idents.
Environment variables :
If the master process fails to establish a connection with a newly launched worker within 60.0 seconds, the worker treats it as a fatal situation and terminates. This timeout can be controlled via environment variable
JULIA_WORKER_TIMEOUT. The value ofJULIA_WORKER_TIMEOUTon the master process specifies the number of seconds a newly launched worker waits for connection establishment.
addprocs(manager::ClusterManager; kwargs...) → List of process identifiersLaunches worker processes via the specified cluster manager.
For example Beowulf clusters are supported via a custom cluster manager implemented in the package
ClusterManagers.jl.The number of seconds a newly launched worker waits for connection establishment from the master can be specified via variable
JULIA_WORKER_TIMEOUTin the worker process’s environment. Relevant only when using TCP/IP as transport.
nprocs()¶Get the number of available processes.
nworkers()¶Get the number of available worker processes. This is one less than
nprocs(). Equal tonprocs()ifnprocs()==1.
procs()¶Returns a list of all process identifiers.
procs(pid::Integer)Returns a list of all process identifiers on the same physical node. Specifically all workers bound to the same ip-address as
pidare returned.
workers()¶Returns a list of all worker process identifiers.
rmprocs(pids...; waitfor=0.0)¶Removes the specified workers. Note that only process 1 can add or remove workers - if another worker tries to call
rmprocs, an error will be thrown. The optional argumentwaitfordetermines how long the first process will wait for the workers to shut down.
interrupt(pids::AbstractVector=workers())¶Interrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted.
interrupt(pids::Integer...)Interrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted.
myid()¶Get the id of the current process.
asyncmap(f, c...) → collection¶Transform collection
cby applying@asyncfto each element.For multiple collection arguments, apply f elementwise.
pmap([::AbstractWorkerPool, ]f, c...; distributed=true, batch_size=1, on_error=nothing, retry_n=0, retry_max_delay=DEFAULT_RETRY_MAX_DELAY, retry_on=DEFAULT_RETRY_ON) → collection¶Transform collection
cby applyingfto each element using available workers and tasks.For multiple collection arguments, apply f elementwise.
Note that
fmust be made available to all worker processes; see Code Availability and Loading Packages for details.If a worker pool is not specified, all available workers, i.e., the default worker pool is used.
By default,
pmapdistributes the computation over all specified workers. To use only the local process and distribute over tasks, specifydistributed=false. This is equivalent toasyncmap.pmapcan also use a mix of processes and tasks via thebatch_sizeargument. For batch sizes greater than 1, the collection is split into multiple batches, which are distributed across workers. Each such batch is processed in parallel via tasks in each worker. The specifiedbatch_sizeis an upper limit, the actual size of batches may be smaller and is calculated depending on the number of workers available and length of the collection.Any error stops pmap from processing the remainder of the collection. To override this behavior you can specify an error handling function via argument
on_errorwhich takes in a single argument, i.e., the exception. The function can stop the processing by rethrowing the error, or, to continue, return any value which is then returned inline with the results to the caller.Failed computation can also be retried via
retry_on,retry_n,retry_max_delay, which are passed through toretryas argumentsretry_on,nandmax_delayrespectively. If batching is specified, and an entire batch fails, all items in the batch are retried.The following are equivalent:
pmap(f,c;distributed=false)andasyncmap(f,c)pmap(f,c;retry_n=1)andasyncmap(retry(remote(f)),c)pmap(f,c;retry_n=1,on_error=e->e)andasyncmap(x->tryretry(remote(f))(x)catche;eend,c)
remotecall(f, id::Integer, args...; kwargs...) → Future¶Call a function
fasynchronously on the given arguments on the specified process. Returns aFuture. Keyword arguments, if any, are passed through tof.
Base.process_messages(r_stream::IO, w_stream::IO, incoming::Bool=true)¶Called by cluster managers using custom transports. It should be called when the custom transport implementation receives the first message from a remote worker. The custom transport must manage a logical connection to the remote worker and provide two
IOobjects, one for incoming messages and the other for messages addressed to the remote worker. Ifincomingistrue, the remote peer initiated the connection. Whichever of the pair initiates the connection sends the cluster cookie and its Julia version number to perform the authentication handshake.
RemoteException(captured)¶Exceptions on remote computations are captured and rethrown locally. A
RemoteExceptionwraps the pid of the worker and a captured exception. ACapturedExceptioncaptures the remote exception and a serializable form of the call stack when the exception was raised.
Future(pid::Integer=myid())¶Create a
Futureon processpid. The defaultpidis the current process.
RemoteChannel(pid::Integer=myid())¶Make a reference to a
Channel{Any}(1)on processpid. The defaultpidis the current process.
RemoteChannel(f::Function, pid::Integer=myid())Create references to remote channels of a specific size and type.
f()is a function that when executed onpidmust return an implementation of anAbstractChannel.For example,
RemoteChannel(()->Channel{Int}(10),pid), will return a reference to a channel of typeIntand size 10 onpid.The default
pidis the current process.
wait([x])¶Block the current task until some event occurs, depending on the type of the argument:
RemoteChannel: Wait for a value to become available on the specified remote channel.Future: Wait for a value to become available for the specified future.Channel: Wait for a value to be appended to the channel.Condition: Wait fornotifyon a condition.Process: Wait for a process or process chain to exit. Theexitcodefield of a process can be used to determine success or failure.Task: Wait for aTaskto finish, returning its result value. If the task fails with an exception, the exception is propagated (re-thrown in the task that calledwait).RawFD: Wait for changes on a file descriptor (seepoll_fdfor keyword arguments and return code)
If no argument is passed, the task blocks for an undefined period. A task can only be restarted by an explicit call to
scheduleoryieldto.Often
waitis called within awhileloop to ensure a waited-for condition is met before proceeding.
fetch(x)¶Waits and fetches a value from
xdepending on the type ofx. Does not remove the item fetched:Future: Wait for and get the value of a Future. The fetched value is cached locally. Further calls tofetchon the same reference return the cached value. If the remote value is an exception, throws aRemoteExceptionwhich captures the remote exception and backtrace.RemoteChannel: Wait for and get the value of a remote reference. Exceptions raised are same as for aFuture.Channel: Wait for and get the first available item from the channel.
remotecall_wait(f, id::Integer, args...; kwargs...)¶Perform a faster
wait(remotecall(...))in one message on theWorkerspecified by worker idid. Keyword arguments, if any, are passed through tof.
remotecall_fetch(f, id::Integer, args...; kwargs...)¶Perform
fetch(remotecall(...))in one message. Keyword arguments, if any, are passed through tof. Any remote exceptions are captured in aRemoteExceptionand thrown.
put!(rr::RemoteChannel, args...)¶Store a set of values to the
RemoteChannel. If the channel is full, blocks until space is available. Returns its first argument.
put!(rr::Future, v)Store a value to a
Futurerr.Futures are write-once remote references. Aput!on an already setFuturethrows anException. All asynchronous remote calls returnFutures and set the value to the return value of the call upon completion.
put!(c::Channel, v)Appends an item
vto the channelc. Blocks if the channel is full.
take!(rr::RemoteChannel, args...)¶Fetch value(s) from a remote channel, removing the value(s) in the processs.
take!(c::Channel)Removes and returns a value from a
Channel. Blocks till data is available.
isready(c::Channel)¶Determine whether a
Channelhas a value stored to it.isreadyonChannels is non-blocking.
isready(rr::RemoteChannel, args...)Determine whether a
RemoteChannelhas a value stored to it. Note that this function can cause race conditions, since by the time you receive its result it may no longer be true. However, it can be safely used on aFuturesince they are assigned only once.
isready(rr::Future)Determine whether a
Futurehas a value stored to it.If the argument
Futureis owned by a different node, this call will block to wait for the answer. It is recommended to wait forrrin a separate task instead or to use a localChannelas a proxy:c=Channel(1)@asyncput!(c,remotecall_fetch(long_computation,p))isready(c)# will not block
close(c::Channel)¶Closes a channel. An exception is thrown by:
put!on a closed channel.take!andfetchon an empty, closed channel.
WorkerPool(workers)¶Create a WorkerPool from a vector of worker ids.
CachingPool(workers::Vector{Int})¶An implementation of an
AbstractWorkerPool.remote,remotecall_fetch,pmapand other remote calls which execute functions remotely, benefit from caching the serialized/deserialized functions on the worker nodes, especially for closures which capture large amounts of data.The remote cache is maintained for the lifetime of the returned
CachingPoolobject. To clear the cache earlier, useclear!(pool).For global variables, only the bindings are captured in a closure, not the data.
letblocks can be used to capture global data.For example:
constfoo=rand(10^8);wp=CachingPool(workers())letfoo=foopmap(wp,i->sum(foo)+i,1:100);end
The above would transfer
fooonly once to each worker.
default_worker_pool()¶WorkerPool containing idle
workers()(used byremote(f)).
remote([::AbstractWorkerPool, ]f) → Function¶Returns a lambda that executes function
fon an available worker usingremotecall_fetch.
remotecall(f, pool::AbstractWorkerPool, args...; kwargs...)Call
f(args...;kwargs...)on one of the workers inpool. Returns aFuture.
remotecall_wait(f, pool::AbstractWorkerPool, args...; kwargs...)Call
f(args...;kwargs...)on one of the workers inpool. Waits for completion, returns aFuture.
remotecall_fetch(f, pool::AbstractWorkerPool, args...; kwargs...)Call
f(args...;kwargs...)on one of the workers inpool. Waits for completion and returns the result.
timedwait(testcb::Function, secs::Float64; pollint::Float64=0.1)¶Waits till
testcbreturnstrueor forsecsseconds, whichever is earlier.testcbis polled everypollintseconds.
@spawn()¶Creates a closure around an expression and runs it on an automatically-chosen process, returning a
Futureto the result.
@spawnat()¶Accepts two arguments,
pand an expression. A closure is created around the expression and run asynchronously on processp. Returns aFutureto the result.
@fetch()¶Equivalent to
fetch(@spawnexpr).
@fetchfrom()¶Equivalent to
fetch(@spawnatpexpr).
@async()¶Like
@schedule,@asyncwraps an expression in aTaskand adds it to the local machine’s scheduler queue. Additionally it adds the task to the set of items that the nearest enclosing@syncwaits for.@asyncalso wraps the expression in aletx=x,y=y,...block to create a new scope with copies of all variables referenced in the expression.
@sync()¶Wait until all dynamically-enclosed uses of
@async,@spawn,@spawnatand@parallelare complete. All exceptions thrown by enclosed async operations are collected and thrown as aCompositeException.
@parallel()¶A parallel for loop of the form :
@parallel[reducer]forvar=rangebodyend
The specified range is partitioned and locally executed across all workers. In case an optional reducer function is specified,
@parallelperforms local reductions on each worker with a final reduction on the calling process.Note that without a reducer function,
@parallelexecutes asynchronously, i.e. it spawns independent tasks on all available workers and returns immediately without waiting for completion. To wait for completion, prefix the call with@sync, like :@sync@parallelforvar=rangebodyend
@everywhere()¶Execute an expression on all processes. Errors on any of the processes are collected into a
CompositeExceptionand thrown. For example :@everywherebar=1
will define
barunder moduleMainon all processes.Unlike
@spawnand@spawnat,@everywheredoes not capture any local variables. Prefixing@everywherewith@evalallows us to broadcast local variables using interpolation :foo=1@eval@everywherebar=$foo
clear!(pool::CachingPool) → pool¶Removes all cached functions from all participating workers.
Base.remoteref_id(r::AbstractRemoteRef) → RRID¶Futures andRemoteChannels are identified by fields:where- refers to the node where the underlying object/storage referred to by the reference actually exists.whence- refers to the node the remote reference was created from. Note that this is different from the node where the underlying object referred to actually exists. For example callingRemoteChannel(2)from the master process would result in awherevalue of 2 and awhencevalue of 1.idis unique across all references created from the worker specified bywhence.Taken together,
whenceandiduniquely identify a reference across all workers.Base.remoteref_idis a low-level API which returns aBase.RRIDobject that wrapswhenceandidvalues of a remote reference.
Base.channel_from_id(id) → c¶A low-level API which returns the backing
AbstractChannelfor anidreturned byBase.remoteref_id(). The call is valid only on the node where the backing channel exists.
Base.worker_id_from_socket(s) → pid¶A low-level API which given a
IOconnection or aWorker, returns thepidof the worker it is connected to. This is useful when writing customserializemethods for a type, which optimizes the data written out depending on the receiving process id.
Returns the cluster cookie.
Base.cluster_cookie(cookie) → cookieSets the passed cookie as the cluster cookie, then returns it.
Multi-Threading¶
This experimental interface supports Julia’s multi-threading capabilities. Types and function described here might (and likely will) change in the future.
Threads.threadid()¶Get the ID number of the current thread of execution. The master thread has ID
1.
Threads.nthreads()¶Get the number of threads available to the Julia process. This is the inclusive upper bound on
threadid().
Threads.@threads()¶A macro to parallelize a for-loop to run with multiple threads. This spawns
nthreads()number of threads, splits the iteration space amongst them, and iterates in parallel. A barrier is placed at the end of the loop which waits for all the threads to finish execution, and the loop returns.
Threads.Atomic{T}()¶Holds a reference to an object of type
T, ensuring that it is only accessed atomically, i.e. in a thread-safe manner.Only certain “simple” types can be used atomically, namely the bitstypes integer and float-point types. These are
Int8...``Int128``,UInt8...``UInt128``, andFloat16...``Float64``.New atomic objects can be created from a non-atomic values; if none is specified, the atomic object is initialized with zero.
Atomic objects can be accessed using the
[]notation:x::Atomic{Int}x[]=1val=x[]
Atomic operations use an
atomic_prefix, such asatomic_add!,atomic_xchg!, etc.
Threads.atomic_cas!{T}(x::Atomic{T}, cmp::T, newval::T)¶Atomically compare-and-set
xAtomically compares the value in
xwithcmp. If equal, writenewvaltox. Otherwise, leavesxunmodified. Returns the old value inx. By comparing the returned value tocmp(via===) one knows whetherxwas modified and now holds the new valuenewval.For further details, see LLVM’s
cmpxchginstruction.This function can be used to implement transactional semantics. Before the transaction, one records the value in
x. After the transaction, the new value is stored only ifxhas not been modified in the mean time.
Threads.atomic_xchg!{T}(x::Atomic{T}, newval::T)¶Atomically exchange the value in
xAtomically exchanges the value in
xwithnewval. Returns the old value.For further details, see LLVM’s
atomicrmwxchginstruction.
Threads.atomic_add!{T}(x::Atomic{T}, val::T)¶Atomically add
valtoxPerforms
x[]+=valatomically. Returns the old (!) value.For further details, see LLVM’s
atomicrmwaddinstruction.
Threads.atomic_sub!{T}(x::Atomic{T}, val::T)¶Atomically subtract
valfromxPerforms
x[]-=valatomically. Returns the old (!) value.For further details, see LLVM’s
atomicrmwsubinstruction.
Threads.atomic_and!{T}(x::Atomic{T}, val::T)¶Atomically bitwise-and
xwithvalPerforms
x[]&=valatomically. Returns the old (!) value.For further details, see LLVM’s
atomicrmwandinstruction.
Threads.atomic_nand!{T}(x::Atomic{T}, val::T)¶Atomically bitwise-nand (not-and)
xwithvalPerforms
x[]=~(x[]&val)atomically. Returns the old (!) value.For further details, see LLVM’s
atomicrmwnandinstruction.
Threads.atomic_or!{T}(x::Atomic{T}, val::T)¶Atomically bitwise-or
xwithvalPerforms
x[]|=valatomically. Returns the old (!) value.For further details, see LLVM’s
atomicrmworinstruction.
Threads.atomic_xor!{T}(x::Atomic{T}, val::T)¶Atomically bitwise-xor (exclusive-or)
xwithvalPerforms
x[]$=valatomically. Returns the old (!) value.For further details, see LLVM’s
atomicrmwxorinstruction.
Threads.atomic_max!{T}(x::Atomic{T}, val::T)¶Atomically store the maximum of
xandvalinxPerforms
x[]=max(x[],val)atomically. Returns the old (!) value.For further details, see LLVM’s
atomicrmwmininstruction.
Threads.atomic_min!{T}(x::Atomic{T}, val::T)¶Atomically store the minimum of
xandvalinxPerforms
x[]=min(x[],val)atomically. Returns the old (!) value.For further details, see LLVM’s
atomicrmwmaxinstruction.
Threads.atomic_fence()¶Insert a sequential-consistency memory fence
Inserts a memory fence with sequentially-consistent ordering semantics. There are algorithms where this is needed, i.e. where an acquire/release ordering is insufficient.
This is likely a very expensive operation. Given that all other atomic operations in Julia already have acquire/release semantics, explicit fences should not be necessary in most cases.
For further details, see LLVM’s
fenceinstruction.
ccall using a threadpool (Experimental)¶
@threadcall((cfunc, clib), rettype, (argtypes...), argvals...)¶The
@threadcallmacro is called in the same way asccallbut does the work in a different thread. This is useful when you want to call a blocking C function without causing the mainjuliathread to become blocked. Concurrency is limited by size of the libuv thread pool, which defaults to 4 threads but can be increased by setting theUV_THREADPOOL_SIZEenvironment variable and restarting thejuliaprocess.Note that the called function should never call back into Julia.
Synchronization Primitives¶
AbstractLock¶Abstract supertype describing types that implement the thread-safe synchronization primitives:
lock,trylock,unlock, andislocked
lock(the_lock)¶Acquires the lock when it becomes available. If the lock is already locked by a different task/thread, it waits for it to become available.
Each
lockmust be matched by anunlock.
unlock(the_lock)¶Releases ownership of the lock.
If this is a recursive lock which has been acquired before, it just decrements an internal counter and returns immediately.
trylock(the_lock) → Success (Boolean)¶Acquires the lock if it is available, returning
trueif successful. If the lock is already locked by a different task/thread, returnsfalse.Each successful
trylockmust be matched by anunlock.
islocked(the_lock) → Status (Boolean)¶Check whether the lock is held by any task/thread. This should not be used for synchronization (see instead
trylock).
ReentrantLock()¶Creates a reentrant lock for synchronizing Tasks. The same task can acquire the lock as many times as required. Each
lockmust be matched with anunlock.This lock is NOT threadsafe. See
Threads.Mutexfor a threadsafe lock.
Mutex()¶These are standard system mutexes for locking critical sections of logic.
On Windows, this is a critical section object, on pthreads, this is a
pthread_mutex_t.See also SpinLock for a lighter-weight lock.
SpinLock()¶Creates a non-reentrant lock. Recursive use will result in a deadlock. Each
lockmust be matched with anunlock.Test-and-test-and-set spin locks are quickest up to about 30ish contending threads. If you have more contention than that, perhaps a lock is the wrong way to synchronize.
See also RecursiveSpinLock for a version that permits recursion.
See also Mutex for a more efficient version on one core or if the lock may be held for a considerable length of time.
RecursiveSpinLock()¶Creates a reentrant lock. The same thread can acquire the lock as many times as required. Each
lockmust be matched with anunlock.See also SpinLock for a slightly faster version.
See also Mutex for a more efficient version on one core or if the lock may be held for a considerable length of time.
Semaphore(sem_size)¶Creates a counting semaphore that allows at most
sem_sizeacquires to be in use at any time. Each acquire must be mached with a release.This construct is NOT threadsafe.
acquire(s::Semaphore)¶Wait for one of the
sem_sizepermits to be available, blocking until one can be acquired.
release(s::Semaphore)¶Return one permit to the pool, possibly allowing another task to acquire it and resume execution.
Cluster Manager Interface¶
This interface provides a mechanism to launch and manage Julia workers on different cluster environments. LocalManager, for launching additional workers on the same host and SSHManager, for launching on remote hosts via ssh are present in Base. TCP/IP sockets are used to connect and transport messages between processes. It is possible for Cluster Managers to provide a different transport.
launch(manager::ClusterManager, params::Dict, launched::Array, launch_ntfy::Condition)¶Implemented by cluster managers. For every Julia worker launched by this function, it should append a
WorkerConfigentry tolaunchedand notifylaunch_ntfy. The function MUST exit once all workers, requested bymanagerhave been launched.paramsis a dictionary of all keyword argumentsaddprocswas called with.
manage(manager::ClusterManager, id::Integer, config::WorkerConfig. op::Symbol)¶Implemented by cluster managers. It is called on the master process, during a worker’s lifetime, with appropriate
opvalues:- with
:register/:deregisterwhen a worker is added / removed from the Julia worker pool. - with
:interruptwheninterrupt(workers)is called. TheClusterManagershould signal the appropriate worker with an interrupt signal. - with
:finalizefor cleanup purposes.
- with
kill(manager::ClusterManager, pid::Int, config::WorkerConfig)¶Implemented by cluster managers. It is called on the master process, by
rmprocs. It should cause the remote worker specified bypidto exit.Base.kill(manager::ClusterManager.....)executes a remoteexit()onpid
init_worker(cookie::AbstractString, manager::ClusterManager=DefaultClusterManager())¶Called by cluster managers implementing custom transports. It initializes a newly launched process as a worker. Command line argument
--workerhas the effect of initializing a process as a worker using TCP/IP sockets for transport.cookieis acluster_cookie().
connect(manager::ClusterManager, pid::Int, config::WorkerConfig) → (instrm::IO, outstrm::IO)¶Implemented by cluster managers using custom transports. It should establish a logical connection to worker with id
pid, specified byconfigand return a pair ofIOobjects. Messages frompidto current process will be read offinstrm, while messages to be sent topidwill be written tooutstrm. The custom transport implementation must ensure that messages are delivered and received completely and in order.Base.connect(manager::ClusterManager.....)sets up TCP/IP socket connections in-between workers.