【问题标题】:Unexpected/Incorrect Results while running SYCL/DPC++ code运行 SYCL/DPC++ 代码时出现意外/错误结果
【发布时间】:2021-11-05 02:06:38
【问题描述】:

我是 SYCl/DPC++ 的初学者。我想打印 10 的倍数,但不是这样,而是用 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;
        });
    });

  for (int i = 0; i <  n; i++) {
    hostArray[i] = sharedArray[i];
    cout<<hostArray[i]<<" "<<sharedArray[i];
    cout<<"\n";
  }
  cout<<"\n";
  return 0;
}

预期结果:

                  0   0
                  10 10
                  20 20
                  30 30
                  40 40
                  50 50
                  60 60
                  70 70
                  80 80
                  90 90

实际输出:

                  0 0
                  0 0
                  0 0
                  0 0
                  0 0
                  0 0
                  0 0
                  0 0
                  0 0
                  0 0

【问题讨论】:

  • 你在那里使用基于 1 的索引吗?
  • 是的,我正在使用基于 1 的索引,以便从 10 而不是 0 开始获得 10 的倍数
  • 好的,但是您知道 C++ 通常使用从零开始的索引,对吧?这看起来像是一个越界数组访问,除了parallel_for,它再次使用正确的索引。
  • 我改过,结果和以前一样
  • edit您的问题并添加预期结果和实际结果。在任何情况下,如果文档没有明确地将这些数组标记为基于 1,则上面的代码是错误的,并且在您运行它时可能会发生任何事情。

标签: c++ parallel-processing sycl intel-oneapi dpc++


【解决方案1】:

您在提交队列和宿主代码中的 for 循环之间缺少障碍。

虽然在主机和设备上确实可以看到 USM 共享内存分配,但不能保证您提交到队列的命令组会在主机中的 for 循环之前执行:提交到队列执行异步写入调用线程。 更新代码如下:

    #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;
            });
        });
      // Wait for completion of all previously submitted command groups
      q.wait();
    
      for (int i = 0; i <  n; i++) {
        hostArray[i] = sharedArray[i];
        cout<<hostArray[i]<<" "<<sharedArray[i];
        cout<<"\n";
      }
      cout<<"\n";
      return 0;
    }

【讨论】:

  • 感谢您查看我的代码,我能够得到预期的结果
猜你喜欢
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多