:@sync

@sync

Wait until all dynamically-enclosed uses of @async, @spawn, @spawnat and @parallel are complete. All exceptions thrown by enclosed async operations are collected and thrown as a CompositeException.

Examples

  1. Wait for completion of async operations:

    julia> @sync begin
               @async println("Task 1")
               @async println("Task 2")
               @async println("Task 3")
           end
    Task 1
    Task 2
    Task 3

    In this example, the @sync macro is used to wait until all the enclosed @async tasks are complete before continuing execution. The output will show the tasks executed in order.

  2. Handle exceptions from async operations:

    julia> try
               @sync begin
                   @async throw(ErrorException("Async Error 1"))
                   @async throw(ErrorException("Async Error 2"))
               end
           catch ex
               println("Caught exception: ", ex)
           end
    Caught exception: CompositeException(ErrorException("Async Error 1"), ErrorException("Async Error 2"))

    In this example, the @sync macro is used to wait for the completion of the enclosed @async tasks. If any of the enclosed tasks throw an exception, the exceptions are collected and thrown as a CompositeException. The catch block can be used to handle the collected exceptions.

  3. Synchronize parallel computations:

    julia> @sync @parallel for i in 1:10
               println("Iteration: ", i)
           end
    Iteration: 1
    Iteration: 2
    Iteration: 3
    Iteration: 4
    Iteration: 5
    Iteration: 6
    Iteration: 7
    Iteration: 8
    Iteration: 9
    Iteration: 10

    In this example, the @sync macro is used in conjunction with @parallel to synchronize the parallel execution of a loop. The @sync ensures that all iterations of the loop are completed before continuing.

Common mistakes example:

julia> @sync begin
           @async println("Task 1")
           println("Task 2")
       end
ERROR: `@async` is not allowed inside non-`Task` context

In this example, the @async macro is used outside the @sync block. The @async macro is only allowed inside @sync, @parallel, or other Task-related contexts. Ensure that @async is used within the appropriate context to avoid this error.

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: