Skip to content

asc_atomic_xor

产品支持情况

  • Ascend 950PR/Ascend 950DT:支持
  • Atlas A3 训练系列产品/Atlas A3 推理系列产品:不支持
  • Atlas A2 训练系列产品/Atlas A2 推理系列产品:不支持
  • Atlas 200I/500 A2 推理产品:不支持
  • Atlas 推理系列产品AI Core:不支持
  • Atlas 推理系列产品Vector Core:不支持
  • Atlas 训练系列产品:不支持

功能说明

对Unified Buffer或Global Memory上address的数值与指定数值val进行原子异或(^)操作,即将address数值异或(^)val的结果赋值到Unified Buffer或Global Memory上。

函数原型

C++
inline int32_t asc_atomic_xor(int32_t *address, int32_t val)
C++
inline uint32_t asc_atomic_xor(uint32_t *address, uint32_t val)
C++
inline int64_t asc_atomic_xor(int64_t *address, int64_t val)
C++
inline uint64_t asc_atomic_xor(uint64_t *address, uint64_t val)

参数说明

表1 参数说明

参数名输入/输出描述
address输出Unified Buffer或Global Memory的地址。
val输入源操作数。

不同数据类型支持的内存范围说明如下:

表2 不同数据类型支持的内存范围

参数数据类型支持的内存空间
int32_t、uint32_tUnified Buffer、Global Memory
int64_t、uint64_tGlobal Memory

返回值说明

Unified Buffer或Global Memory上的初始数据。

约束说明

原子操作保证对同一地址的读改写过程具有原子性,但不保证多个线程之间的执行顺序。对于依赖接口返回值判断线程先后顺序的场景,结果可能随线程调度变化而不同。

需要包含的头文件

使用该接口需要包含"simt_api/device_atomic_functions.h"头文件。

C++
#include "simt_api/device_atomic_functions.h"

实测验证

实测环境:Ascend 950PR,CANN 9.0.0,bisheng --enable-simt --npu-arch=dav-3510

覆盖项初始值操作期望结果实测结果
uint32_t Global Memory0128个线程各执行asc_atomic_xor(address, 1U)0通过

本用例执行偶数次异或,最终值回到0,用于验证原子异或在多线程竞争写同一地址时结果一致。

调用示例

示例场景为:多个线程检查事件是否命中,命中时使用asc_atomic_xor接口翻转共享奇偶标志。最终值为1表示命中次数为奇数,0表示命中次数为偶数。输入参数说明如下:

名称说明
hit每个元素表示一个线程是否命中事件,1为命中,0为未命中。
parityGlobal Memory中的奇偶标志,kernel启动前清零。
n输入元素个数。

核心代码实现如下:

  • SIMT编程场景:

    C++
    __global__ __launch_bounds__(256) void compute_hit_parity(uint32_t *parity,
                                                             uint32_t *hit,
                                                             uint32_t n)
    {
        uint32_t idx = blockIdx.x * blockDim.x + threadIdx.x;
        if (idx >= n) {
            return;
        }
    
        if (hit[idx] != 0U) {
            asc_atomic_xor(parity, 1U);
        }
    }
    
  • SIMD与SIMT混合编程场景:

    SIMD与SIMT混合编程场景,需要显式使用地址空间限定符表示地址空间:__gm__表示Global Memory内存空间,__ubuf__表示Unified Buffer内存空间。

    C++
    __simt_vf__ __launch_bounds__(1024) inline void compute_hit_parity(__gm__ uint32_t *parity,
                                                                      __gm__ uint32_t *hit,
                                                                      uint32_t n)
    {
        uint32_t idx = blockIdx.x * blockDim.x + threadIdx.x;
        if (idx >= n) {
            return;
        }
    
        if (hit[idx] != 0U) {
            asc_atomic_xor(parity, 1U);
        }
    }
    

输出结果示例如下:

Text
hit: 1, 0, 1, 1
parity: 1 // 共有3次命中,奇数次翻转后结果为1

免责声明:本站内容由 asc-devkit 仓 master 分支自动编译生成,属于持续开发版本,可能存在缺陷,仅供预览与参考。如需稳定及商用资料,请查阅官方 昇腾社区