AtomicExch

Applicability

Product

Supported

Atlas 350 Accelerator Card

Atlas A3 training product/Atlas A3 inference product

x

Atlas A2 training product/Atlas A2 inference product

x

Atlas 200I/500 A2 inference product

x

Atlas inference product AI Core

x

Atlas inference product Vector Core

x

Atlas training product

x

Function Usage

Performs an atomic exchange operation in the global memory. Specifically, it reads data from the specified global memory address, stores the new value back to the same address, and returns the old value.

Prototype

1
2
template <typename T>
__aicore__ inline T AtomicExch(__gm__ T *address, T value)

Parameters

Table 1 Template parameters

Parameter

Description

T

Operand data type.

For the Atlas 350 Accelerator Card, the supported data types are uint32_t and uint64_t.

Table 2 Parameters

Parameter

Input/Output

Description

address

Input

Global memory address.

value

Input

Scalar value. Its data type can be the same as that specified by the address.

Returns

Data before the atomic operation is performed on the global memory address.

Constraints

The atomic operation involves scalar computation. If the Scalar Unit and DMA unit (MTE2/MTE3) have data dependencies during global memory read and write, you need to insert synchronization as needed.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Pass the address of the global data to initialize dstGlobal and dstLocal.
dstGlobal.SetGlobalBuffer(reinterpret_cast<__gm__ T *>(dstGm), dataSize);

LocalTensor<T> dstLocal = inQueueX.AllocTensor<T>();
uint32_t value = 2;
uint32_t a = AscendC::AtomicExch(reinterpret_cast<__gm__ uint32_t *>(dstGm), values);
// The movement operation can be performed only after the atomic operation is complete. There are data dependencies.
event_t eventIdSToMte2 = static_cast<event_t>(GetTPipePtr()->AllocEventID<HardEvent::S_MTE2>());
// Manually insert the MTE2 wait for Scalar Unit synchronization.
SetFlag<HardEvent::S_MTE2>(eventIdSToMte2);
WaitFlag<HardEvent::S_MTE2>(eventIdSToMte2);
DataCopy(dstLocal, dstGlobal, dataSize);
// ...

Assume that the preceding function is executed on three cores, and core 1, core 2, and core 3 are scheduled in sequence. The result example is as follows:

Original global memory data dst: [1,1,1,1,1,...,1] 
Core 1:
Global memory data dst after atomic computation: [2,1,1,1,1,...,1] 
Return value a: 1
Core 2:
Global memory data dst after atomic computation: [2,1,1,1,1,...,1] 
Return value a: 2
Core 3:
Global memory data dst after atomic computation: [2,1,1,1,1,...,1] 
Return value a: 2