C Library Functions  - atomic_cas (3)

NAME

ATOMIC_CAS(3) - [ATOMIC] Atomically compare and swap a set of values

SYNOPSIS

call atomic_cas (atom, old, compare, new [,stat] )

         subroutine atomic_cas (atom, old, compare, new, stat)

CHARACTERISTICS

DESCRIPTION

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_ENV’s STAT_STOPPED_IMAGE and if the remote image has failed, the value STAT_FAILED_IMAGE.

OPTIONS

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.
o OLD : Scalar of the same type and kind as ATOM. It receives the value of ATOM before the operation.
o COMPARE : Scalar variable of the same type and kind as ATOM. Used for comparison.
o NEW : Scalar variable of the same type as ATOM. If kind is different, the value is converted to the kind of ATOM. It is given the new value from ATOM if the comparison succeeds.
o STAT : (optional) Scalar default-kind integer variable.

EXAMPLES

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, me

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

Expected Output (4 images, order varies)

        > 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

STANDARD

Fortran 2008 and later, per TS 18508

SEE ALSO

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
Generated by manServer 1.08 from 97e254e7-5d2e-45bd-b49d-91877aa3593a using man macros.