【问题标题】:How to use a struct array in thrust::sort?如何在推力::排序中使用结构数组?
【发布时间】:2014-02-17 00:58:24
【问题描述】:

我是 CUDA 开发的新手,我正在尝试使用推力库的排序方法对结构数组进行排序。我的结构是这样的:

#define N 307200    
struct distanceVector {
   Point3D a, b;
   float distance;
};

我想按“距离”对数组进行排序,但是,排序函数需要两个随机访问迭代器,而且由于我没有使用向量,所以我没有任何向量。我试过做这样的事情:

bool distance_sort(distanceVector A, distanceVector B){
   return (A.distance > B.distance);
}

distanceVector * MyStructArray;
cudaMalloc((void**)&MyStructArray, sizeof(distanceVector) * N);
//LAUNCH KERNEL WHICH FILLS MYSTRUCTARRAY AND THEN...
thrust::sort(MyStructArray, MyStructArray + N, distance_sort);

...我在 [thrust's guide][1] 中看到了一个示例:

#include <thrust/sort.h>
#include <thrust/functional.h>
...
const int N = 6;
int A[N] = {1, 4, 2, 8, 5, 7};
thrust::stable_sort(A, A + N, thrust::greater<int>());
// A is now {8, 7, 5, 4, 2, 1}

虽然它可以编译,但在执行期间我收到“访问冲突读取位置 0x405e041c”。错误。 调试应用程序时,在 insert_sort.h 文件中的此部分停止:

for(RandomAccessIterator i = first + 1; i != last; ++i)
  {
    value_type tmp = *i;

    if (wrapped_comp(tmp, *first)).......

有没有办法在不使用推力向量的情况下解决这个问题?

【问题讨论】:

  • 展示你如何定义NMyStructArray
  • 我添加了您建议的更改

标签: c++ arrays sorting cuda thrust


【解决方案1】:

好的,所以我发现了我的错误。问题是我试图在设备上分配的内存上使用推力。我尝试先将 MyStructArray 复制到主机设备,然后使用推力的排序,它工作得很好。为了在设备的内存上工作,我必须使用推力::device_ptr 指针(MyStructArray)。 希望这对其他人有帮助。

【讨论】:

    【解决方案2】:

    我尝试使用thrust::sortthrust::host_vector&lt;struct&gt;thrust::device_vector&lt;struct&gt; 进行排序。它们都在我的设备上运行良好。

    这是我的代码:

    #include <bits/stdc++.h>
    #include <stdio.h>
    #include <cuda_runtime.h>
    #include <thrust/host_vector.h>
    #include <thrust/device_vector.h>
    #include <thrust/sort.h>
    #include <time.h>
    #include <thrust/functional.h>
    const int MAXN = 1e2;
    typedef struct Node {
        int x, y;
        __host__ __device__ bool operator < (const Node& a) const {
            if (x == a.x) {
                return x ? y<a.y : y>a.y;
            }else 
                return x < a.x;
        }
    }Node;
    int main() {
        thrust::host_vector<Node> h(MAXN),ne(MAXN);
        for (int i = 0; i < MAXN; i++) {
            h[i].x = rand() % 2;
            h[i].y = rand() % 997;
        }
        thrust::device_vector<Node> d = h;
        thrust::sort(h.begin(), h.end());
        thrust::sort(d.begin(), d.end());
        ne = d;
        for (int i = 0; i < MAXN; i++) {
            std::cout << h[i].x << " " << h[i].y << "  |  " << ne[i].x << " " << ne[i].y << std::endl;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-17
      • 2021-05-27
      • 2015-09-03
      • 2021-12-18
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 2014-09-06
      • 2019-11-27
      相关资源
      最近更新 更多