You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行SYCL/DPC++代码得到非预期全0结果,无法输出10的倍数

问题原因

SYCL队列提交的设备任务是异步执行的,你提交parallel_for运算任务后没有等待任务执行完成,主机端就直接读取了sharedArray的数值,此时设备端的计算还没完成,读取到的还是内存初始化的默认值0,所以输出全为0。

解决方法

在提交完计算任务后、主机读取共享数组前,添加队列同步操作,等待设备端任务执行完成即可。另外注意USM申请的内存需要主动释放,避免内存泄漏。

修正后代码

#include <CL/sycl.hpp>
#include<iostream>
using namespace std;
using namespace sycl;
constexpr int n = 10;

int main() {
  queue q;
  int *hostArray = malloc_host<int>(n, q);
  int *sharedArray = malloc_shared<int>(n, q);

  for (int i = 0; i < n; i++)
    hostArray[i] = i;
  q.submit([&](handler &h) {
      h.parallel_for(n, [=](id<1> i) {
          sharedArray[i] = hostArray[i] * 10;
        });
    });
  // 新增:等待队列中所有任务执行完成
  q.wait();

  for (int i = 0; i <  n; i++) {
    hostArray[i] = sharedArray[i];
    cout<<hostArray[i]<<" "<<sharedArray[i];
    cout<<"\n";
  }
  cout<<"\n";
  // 新增:释放USM申请的内存
  free(hostArray, q);
  free(sharedArray, q);
  return 0;
}

内容的提问来源于stack exchange,提问作者sv6

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:06:03