Example 17-7. Example:
The sync statement allows barrier synchronization between threads attached to the same synchronization object. A thread executing a sync blocks until all threads attached to the same object are also blocking on sync (or have terminated). The sync must be syntactically enclosed in a par statement.
NOTE: A gate is associated with the par statement, and all threads syntactically created within the par statement ( including the special thread that executes the body of the par statement) are attached to this gate,Unlike conventional barriers, the sync statement does not require all threads to reach the sync - only the ones that are currently attached to the gate. This permits some thread (some iterations of a parloop, for example) to terminate early.
Example 17-8. This code applies 'phase1' and 'phase2' to each element of an array, waiting for all 'phase1' before beginning 'phase2':
parloop e::= a.elt!; do e.phase1; end; parloop e::= a.elt!; do e.phase2; end;
Example 17-9. This code does the same thing without iterating over the elements for each phase. A single thread is forked for each element. Each thread executes 'phase1', the sync, and 'phase2'. The thread executing the par waits for all threads to terminate before proceeding.
parloop e::= a.elt! do e.phase1; sync; e.phase2; end;
Because local variables declared in the parloop become unique to each thread, the explicit sync can be useful to allow convenient passing of state from one phase to another through the thread's local variables, instead of using an intermediate array with one element for each thread.