:@spawnat
@spawnat
Accepts two arguments, p
and an expression. A closure is created around the expression and run asynchronously on process p
. Returns a RemoteRef
to the result.
Examples
-
Asynchronously execute an expression on a specific process:
julia> p = 2; # Process number julia> result = @spawnat p begin a = 10 b = 20 a + b end RemoteRef{Channel{Any}}(2, 1, 3, nothing) julia> fetch(result) 30
In this example, the expression
a + b
is executed asynchronously on process 2 using@spawnat
. The result is stored in aRemoteRef
object, which can be fetched later usingfetch
. -
Use variables from the calling scope inside the expression:
julia> p = 3; # Process number julia> x = 5; julia> y = 2; julia> result = @spawnat p x * y RemoteRef{Channel{Any}}(3, 1, 4, nothing) julia> fetch(result) 10
Here, the variables
x
andy
from the calling scope are used inside the expressionx * y
. The result is fetched from theRemoteRef
object and returned. -
Handle complex expressions with multiple lines:
julia> p = 1; # Process number julia> result = @spawnat p begin sum = 0 for i in 1:5 sum += i end sum end RemoteRef{Channel{Any}}(1, 1, 2, nothing) julia> fetch(result) 15
In this example, a multi-line expression is executed asynchronously on process 1. The loop calculates the sum of numbers from 1 to 5, and the final result is fetched from the
RemoteRef
.
Common mistake example:
julia> p = 4; # Process number
julia> result = @spawnat p a + b
ERROR: UndefVarError: a not defined
In this example, the variables a
and b
used inside the expression are not defined in the calling scope. Make sure to define and assign values to the variables before using them in @spawnat
.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.