ATOMIC_CAS(3) - [ATOMIC] Atomically compare and swap a set of values
call atomic_cas (atom, old, compare, new [,stat] )
subroutine atomic_cas (atom, old, compare, new, stat)
ATOMIC_CAS(ATOM, OLD, COMPARE, NEW, STAT) atomically compares the value of ATOM with COMPARE. If they are equal, ATOM is set to NEW, and OLD receives the previous value of ATOM. If not equal, ATOM is unchanged, and OLD still receives the current value of ATOM.
ATOMIC_CAS is useful for implementing locks or conditional updates.
Only one image’s NEW value is set if multiple images attempt the operation simultaneously.
When STAT is present and the invocation was successful, it is assigned the value 0. If it is present and the invocation has failed, it is assigned a positive value; in particular, for a coindexed ATOM, if the remote image has stopped, it is assigned the value of ISO_FORTRAN_ENVs STAT_STOPPED_IMAGE and if the remote image has failed, the value STAT_FAILED_IMAGE.
STAT (optional): A scalar default-kind integer. Set to 0 on success, or a positive value on failure.
o |
ATOM : Scalar coarray or coindexed variable of either integer type
with ATOMIC_INT_KIND kind or logical type with kind
ATOMIC_LOGICAL_KIND.
| ||||||||
Sample program:
program demo_atomic_cas_example use iso_fortran_env implicit none integer(atomic_int_kind) :: lock[*] integer(atomic_int_kind) :: old integer :: stat, meExpected Output (4 images, order varies)if (this_image() == 1) lock = 0 sync all
me = this_image() call atomic_cas(lock[1], old, 0, me, stat)
if (stat /= 0) then print *, "Image", me, ": Failed with STAT =", stat else print *, "Image", me, ": Old =", old, ", New =", lock[1] end if sync all
if (this_image() == 1) print *, "Final lock:", lock end program demo_atomic_cas_example
> Image 1: Old = 0, New = 1 > Image 2: Old = 1, New = 1 > Image 3: Old = 1, New = 1 > Image 4: Old = 1, New = 1 > Final lock: 1
Fortran 2008 and later, per TS 18508
ATOMIC_DEFINE(3), ATOMIC_REF(3), ISO_FORTRAN_ENV(3)
See ISO_FORTRAN_ENV for constants like ATOMIC_INT_KIND, STAT_STOPPED_IMAGE, and STAT_FAILED_IMAGE.
Fortran intrinsic descriptions
Nemo Release 3.1 | atomic_cas (3) | June 29, 2025 |