<ATOMIC_CAS Example Program>

Module value_module
  Use iso_fortran_env
  Integer(atomic_int_kind) :: value[*] = 1
End Module
Program atomic_cas_example
  Use value_module
  ! Images compete by calculating the a possible next value for VALUE.
  ! Whichever image wins the compare-and-swap replaces the value and prints it.
  Integer(atomic_int_kind) newvalue,oldvalue,valuewas
  Logical me
  oldvalue = 1
  Do
    newvalue = calculate_new_value(oldvalue)
    Call atomic_cas(Atom=value[1],New=newvalue,Old=valuewas,Compare=oldvalue)
    me = oldvalue==valuewas
    If (me) Then
      oldvalue = newvalue
      Print 1,This_Image(),newvalue
1     Format(1X,'Image ',I0,' calculated the new value to be ',I0)
    Else
      oldvalue = valuewas
    End If
    If (oldvalue>2**24) Exit
  End Do
  If (me) Then
    Print *,'End of sequence'
  End If
Contains
  Integer(atomic_int_kind) Function calculate_new_value(old)
    Integer(atomic_int_kind),Intent(In) :: old
    calculate_new_value = old**2 - old + 3
  End Function
End Program

■ Execution Results

 Image 2 calculated the new value to be 3
 Image 2 calculated the new value to be 5553
 Image 3 calculated the new value to be 75
 Image 4 calculated the new value to be 30830259
 End of sequence
 Image 1 calculated the new value to be 9

(This is with four images. The mixing of output records from the different images is indeterminate.)