Main Content


Atomically exchange a variable in global or shared memory with the specified value

Since R2021b



    [A,oldA] = gpucoder.atomicExch(A,B) atomically exchanges the value of A in global or shared memory with the value in B and writes the result back into A. The operation is atomic in a sense that the entire read-modify-write operation is guaranteed to be performed without interference from other threads. The order of the input and output arguments must match the syntax provided.


    collapse all

    Perform a simple atomic exchange operation by using the gpucoder.atomicExch function and generate CUDA® code that calls corresponding CUDA atomicExch() APIs.

    In one file, write an entry-point function myAtomicExch that accepts matrix inputs a and b.

    function a = myAtomicExch(a,b)
    for i =1:numel(a)
        [a(i),~] = gpucoder.atomicExch(a(i), b);

    To create a type for a matrix of doubles for use in code generation, use the coder.newtype function.

    A = coder.newtype('single', [1 30], [0 1]);
    B = coder.newtype('single', [1 1], [0 0]);
    inputArgs = {A,B};

    To generate a CUDA library, use the codegen function.

    cfg = coder.gpuConfig('lib');
    cfg.GenerateReport = true;
    codegen -config cfg -args inputArgs myAtomicExch -d myAtomicExch

    The generated CUDA code contains the myAtomicExch_kernel1 kernel with calls to the atomicExch() CUDA APIs.

    // File:
    static __global__ __launch_bounds__(1024, 1) void myAtomicExch_kernel1(
        const real32_T b, const int32_T i, real32_T a_data[])
      uint64_T loopEnd;
      uint64_T threadId;
      for (uint64_T idx{threadId}; idx <= loopEnd; idx += threadStride) {
        int32_T b_i;
        b_i = static_cast<int32_T>(idx);
        atomicExch(&a_data[b_i], b);
    void myAtomicExch(real32_T a_data[], int32_T a_size[2], real32_T b)
      dim3 block;
      dim3 grid;
        cudaMemcpy(gpu_a_data, a_data, a_size[1] * sizeof(real32_T),
        myAtomicExch_kernel1<<<grid, block>>>(b, i, gpu_a_data);
        cudaMemcpy(a_data, gpu_a_data, a_size[1] * sizeof(real32_T),

    Input Arguments

    collapse all

    Operands, specified as scalars, vectors, matrices, or multidimensional arrays. Inputs A and B must satisfy the following requirements:

    • Have the same data type.

    • Have the same size or have sizes that are compatible. For example, A is an M-by-N matrix and B is a scalar or 1-by-N row vector.

    Data Types: single | int32 | uint32 | uint64


    • Function handle input to the gpucoder.stencilKernel pragma cannot contain calls to atomic functions. For example,

      out1 = gpucoder.stencilKernel(@myAtomicExch,A,[3 3],'same',B);

    Version History

    Introduced in R2021b