<LOCK Example Program>

Program lock_example
  Use Iso_Fortran_Env
  Type(lock_type) :: worklock[*]
  Type work_type
    Integer value
    Logical avail,done
  End Type
  Type(work_type) :: work(10)[*] = work_type(0,.True.,.False.)
  !
  ! Only the WORK variable on image 1 is used, to keep track.
  ! Similarly, only the WORKLOCK variable on image 1 is used.
  !
  Integer i
  Do
    Lock(worklock[1])
    Do i=1,Size(work)
      If (work(i)[1]%avail) Then
        ! Unset avail while we still hold the lock.
        work(i)[1]%avail = .False.
        Exit
      End If
    End Do
    Unlock(worklock[1])
    If (i>Size(work)) Exit ! No work available.
    !
    ! A real program would do some real work here.
    ! This example will just assign I to the value on image 1.
    !
    work(i)[1]%value = i
    work(i)[1]%done = .True.
  End Do
  ! Wait for all images to finish the work.
  Sync All
  ! Image 1 will check the results.
  If (This_Image()==1) Then
    Do i=1,Size(work)
      If (.Not.work(i)%done) Error Stop 'Work was not done'
    End Do
    Print *,'Work complete'
  End If
End Program

■ Execution Results

 Work complete