2012-08-05 40 views
1

我试图使用推力指数为每个给设备矢量某些值 这里是代码如何获得推力的foreach

const uint N = 222222; 
struct assign_functor 
{ 
    template <typename Tuple> 
    __device__ 
    void operator()(Tuple t) 
    { 
    uint x = threadIdx.x + blockIdx.x * blockDim.x; 
    uint y = threadIdx.y + blockIdx.y * blockDim.y; 
    uint offset = x + y * blockDim.x * gridDim.x; 

    thrust::get<0>(t) = offset; 
    } 
}; 
int main(int argc, char** argv) 
{ 

    thrust::device_vector <float> d_float_vec(N); 

    thrust::for_each(
    thrust::make_zip_iterator( 
     thrust::make_tuple(d_float_vec.begin()) 
    ), 
    thrust::make_zip_iterator( 
     thrust::make_tuple(d_float_vec.end()) 
    ), 
    assign_functor() 
); 

    std::cout<<d_float_vec[10]<<" "<<d_float_vec[N-2] 
} 

d_float_vec的输出[N-2]被认为是222220;但事实证明1036.我的代码怎么了?

我知道我可以使用thrust :: sequence给这个向量赋一个序列值。我只想知道如何获得推力foreach函数的真实指数。谢谢!

+0

为什么输出应该是N-2? – talonmies 2012-08-05 13:31:12

+0

uint x = threadIdx.x + blockIdx.x * blockDim.x; uint y = threadIdx.y + blockIdx.y * blockDim.y; uint offset = x + y * blockDim.x * gridDim.x;偏移量是索引。我希望每个矢量都有自己的索引 – user1536720 2012-08-05 14:37:28

+0

是的,但是您隐式假定每个线程正好处理数组中的1个输出点,并且在您计算的2D线索索引与数组中的某个位置之间存在直接关系。这些事情都不一定是真的。 – talonmies 2012-08-05 15:11:39

回答

2

正如在评论中指出,你的做法是绝不可能的工作,因为你承担了多项关于thrust::for_each内部工作这可能是不正确的,包括事物的方式:

  • 您隐含假设了for_each使用单个线程来处理每个输入元素。这几乎肯定不是这样;在操作过程中推力将更有可能处理每个螺纹的多个元素。
  • 您还假定执行顺序是为了让第N个线程处理第N个数组元素。这可能不是这种情况,并且在不能已知的顺序,可能会发生执行先验
  • 您假设for_each处理整个输入数据在单个内核laumch

推力算法应设置视为内部操作未定义的黑盒子,并且不需要他们的知识来实现​​用户定义的仿函数。在你的例子中,如果你需要一个函子内部的顺序索引,传递一个计数迭代器。重新写你的榜样的一个方法是这样的:

#include "thrust/device_vector.h" 
#include "thrust/for_each.h" 
#include "thrust/tuple.h" 
#include "thrust/iterator/counting_iterator.h" 

typedef unsigned int uint; 
const uint N = 222222; 
struct assign_functor 
{ 
    template <typename Tuple> 
    __device__ 
    void operator()(Tuple t) 
    { 
    thrust::get<1>(t) = (float)thrust::get<0>(t); 
    } 
}; 

int main(int argc, char** argv) 
{ 
    thrust::device_vector <float> d_float_vec(N); 
    thrust::counting_iterator<uint> first(0); 
    thrust::counting_iterator<uint> last = first + N; 

    thrust::for_each(
    thrust::make_zip_iterator( 
     thrust::make_tuple(first, d_float_vec.begin()) 
    ), 
    thrust::make_zip_iterator( 
     thrust::make_tuple(last, d_float_vec.end()) 
    ), 
    assign_functor() 
); 

    std::cout<<d_float_vec[10]<<" "<<d_float_vec[N-2]<<std::endl; 
} 

这里的计数迭代器获取的元组与数据阵列一起传递,允许其对应于数据阵列条目的顺序索引函子访问它正在处理。

+0

谢谢!真的很感激它! – user1536720 2012-08-06 02:57:32