:@everywhere

@everywhere

Execute an expression on all processes. Errors on any of the processes are collected into a CompositeException and thrown.

Examples

  1. Execute an expression on all processes:

    julia> @everywhere begin
             x = 2
             println(x * myid())
           end
    2
    4
    6
    8

    This example executes the given expression on all processes. In this case, it multiplies the value of x with the process ID (myid()) on each process and prints the result.

  2. Use @everywhere with a function:

    julia> @everywhere function greet(name)
             println("Hello, $name! I am process $myid().")
           end
    
    julia> @everywhere greet("Julia")
    Hello, Julia! I am process 2.
    Hello, Julia! I am process 3.
    Hello, Julia! I am process 4.
    Hello, Julia! I am process 5.

    This example defines a greet function and uses @everywhere to make it available on all processes. It then invokes the greet function with the argument "Julia" on each process.

  3. Handling errors with @everywhere:
    julia> @everywhere begin
             error("Oops, an error occurred on process $myid().")
           end
    ERROR: On worker 2:
    UndefVarError: error not defined
    ...
    CompositeException:
    4 exceptions occurred while handling task Task (worker=2):
    ...

    In this example, an error is intentionally raised on each process using error. The errors are collected into a CompositeException and thrown. Each process will display its respective error message.

Common mistake example:

julia> @everywhere x = 10
ERROR: UndefVarError: x not defined
...

In this example, the variable x is not defined before using it with @everywhere. To avoid this error, ensure that all variables used in the expression are defined before executing it with @everywhere.

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.

*Required Field
Details

Checking you are not a robot: