Main Content

labBarrier

(Not recommended) Synchronize workers in an spmd block

    labBarrier is not recommended. Use spmdBarrier instead. For more information, see Version History.

    Description

    example

    labBarrier stops all workers in the current spmd block or communicating job from executing code until every worker calls labBarrier.

    Tip

    When you offload computations using parfor and parfeval, each computation is run by only one worker at a time. These workers are independent and do not communicate with each other. If you use labBarrier on these workers, the function has no effect.

    Use labBarrier when you need to synchronize workers, such as when workers use shared resources such as a file handle.

    If numlabs is equal to 1, execution continues immediately. numlabs is equal to 1 outside of an spmd block or communicating job.

    Examples

    collapse all

    This example shows how to use labBarrier to synchronize workers in an spmd block.

    Create a parallel pool with 4 workers. By default, spmd is supported on all process-backed pools.

    parpool(4);

    When you execute an spmd block after creating a parallel pool, by default all available workers in the pool will run the code inside the spmd block.

    Create an spmd block, and run pause on each worker for a random amount of time to simulate some computationally expensive work. Use tic and toc to time the execution on each worker.

    spmd
        tic
        pause(5*rand);
        toc
    end
    Worker 2: 
      Elapsed time is 0.702969 seconds.
    Worker 3: 
      Elapsed time is 1.807292 seconds.
    Worker 1: 
      Elapsed time is 4.651690 seconds.
    Worker 4: 
      Elapsed time is 4.694443 seconds.

    To synchronize the workers after each worker runs pause, use labBarrier. In the following code, all workers wait for the slowest worker to finish its computation. The elapsed time on each worker is now the same, except for slight numerical noise.

    spmd
        tic
        pause(5*rand);
        labBarrier;
        toc
    end
    Lab 1: 
      Elapsed time is 4.758529 seconds.
    Lab 2: 
      Elapsed time is 4.758529 seconds.
    Lab 3: 
      Elapsed time is 4.743785 seconds.
    Lab 4: 
      Elapsed time is 4.743739 seconds.

    Version History

    Introduced before R2006a

    expand all

    See Also