Thrust在主机上运行自定义函子的结果不正确

时间:2013-08-17 09:31:23

标签: c++ cuda thrust

当我尝试实现任何仿函数时,我得到了不好的结果。例如,我尝试了类似于thrust::negate<T>的否定函子 下面是使用内置否定函数生成良好结果的示例代码:

int data[10] = {-5, 0, 2, -3, 2, 4, 0, -1, 2, 8};
int out[10];
thrust::negate<int> op;
thrust::transform(data, data + 10, out, op);

out变量变为{5, 0, -2, 3, -2, -4, 0, 1, -2, -8},但是当我实现我自己的仿函数时,如

struct NegateFunctor{
__host__ __device__
    int operator()(const int &val) const {
        return -val;
}
};

并将其称为thrust::transform(data, data + 10, out, NegateFunctor()) out包含{-858993460, -858993460, -858993460, -858993460, -858993460, -858993460, -858993460, -858993460, -858993460, -858993460}

我在64位计算机上使用Visual Studio 2010,5.0 CUDA。

由于

1 个答案:

答案 0 :(得分:1)

如果我编译并运行您的代码(仅修改为添加了thrust::transform调用结果的打印):

#include <thrust/transform.h>
#include <thrust/functional.h>

struct NegateFunctor{
    __host__ __device__
        int operator()(const int &val) const {
            return -val;
    }
};

int main(int argc, char** argv){
    int data[10] = {-5, 0, 2, -3, 2, 4, 0, -1, 2, 8};
    int out[10];
    //thrust::negate<int> op;
    thrust::transform(data, data + 10, out, NegateFunctor());
      for(int i=0; i<10; i++) {
        std::cout << data[i] << " " << out[i] << std::endl;
    }

    return 0;
}

我得到了这个(OS 10.6.7上的CUDA 5.0):

$ nvcc thrust_neg2.cu 
$ ./a.out
-5 5
0 0
2 -2
-3 3
2 -2
4 -4
0 0
-1 1
2 -2
8 -8

这似乎是正确的。如果您没有看到相同的结果,那么这是您正在使用的工具链的特定问题,或者您没有告诉我们的其他原因导致问题。

编辑:从你在调试模式下使用nvcc构建的注释中可以看出,已知这种注释不适用于Thrust。我建议只构建代码以便发布。如果问题仍然存在,这应该是对Thrust开发人员的错误报告,而不是Stack Overflow问题。

相关问题