Parallel Programming Guide for HP-UX Systems

Parallel synchronization
Synchronizing code
Chapter 8 149
C$DIR NEXT_TASK
CONTRIB2 = 0.0
DO I = 1, N
CONTRIB2 = CONTRIB2 + FUNC2(J)
ENDDO
.
.
.
C$DIR CRITICAL_SECTION (SUM_GATE)
GLOBAL_SUM = GLOBAL_SUM + CONTRIB2
C$DIR END_CRITICAL_SECTION
.
.
.
C$DIR END_TASKS
LOCK = FREE_GATE(SUM_GATE)
Here, both parallel tasks must access the shared GLOBAL_SUM variable.
To ensure that GLOBAL_SUM is updated by only one task at a time, it is
placed in a critical section. The critical sections both reference the
SUM_GATE variable. This variable is unlocked on entry into the parallel
code (gates are always unlocked when they are allocated).
When one task reaches the critical section, the CRITICAL_SECTION
directive automatically locks SUM_GATE. The END_CRITICAL_SECTION
directive unlocks SUM_GATE on exit from the section. Because access to
both critical sections is controlled by a single gate, the sections must
execute one at a time.
Example 8-5 Gated critical sections
Gated critical sections are also useful in loops containing multiple
critical sections when there are dependences between the critical
sections. If no dependences exist between the sections, gates are not
needed. The compiler automatically supplies a unique gate for every
critical section lacking a gate.
The C example below uses gates so that threads do not update at the
same time, within a critical section:
static far_shared float absum;
static gate_t gate1;
int adjb[...];
.
.
.
lock = alloc_gate(&gate1);