cuda中,类似于std::vector的容器,__device_vector 的使用方式

起因

由于要将剔除最小连通域中 std:;vetor 这个数据容器,在 kernel 核函数也有类似的使用,所以,查阅资料等百度,完后就找到了 thrust:: 中的 __host_vector, 和 device_vector 这两个东西。然而发现,其依旧需要在本地代码段中来 提前扩展其大小,而不能在kernel 中使用…不过就当记录一下吧,为了以后可以直接拿来使用

代码

//先加载需要 的头文件
//添加cuda数组.
#include <thrust/reduce.h>
#include <thrust/sequence.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>

核函数

__global__ void nestedHelloWorld(int const iSize, int iDepth, int2* vecLists, int vecListSize)
{
	int tid = threadIdx.x;
	printf("Recursion=%d: Hello World from thread %d block %d\n", iDepth, tid, blockIdx.x);

	if (iSize == 1) return;
	int nthreads = iSize >> 1;

	if (tid == 0 && nthreads > 0)
	{
		printf("-------> nested execution depth: %d\n", iDepth);
	}

	for (int i = 0; i < vecListSize; i++)
	{
		int2 temp;
		temp.x = i;
		temp.y = i * 10;
		vecLists[i] = temp;
		// vecLists[i];
		//printf("threadIdx: %d  int2: %d  %d\n",threadIdx.x, temp.x, temp.y);
	}
}



本地函数:
void IteratorMyselfTest()
{
	thrust::device_vector<int2> vecLists;
	vecLists.resize(200);
		
	//这里需要转为一级指针.,最后将参数传进去.
	int2* vecListPtr = thrust::raw_pointer_cast(&vecLists[0]);
	int vecListSize = vecLists.size();

	nestedHelloWorld << <1, 10 >> > (iszie, idepth, vecListPtr, vecListSize);
	
	//打印
	for (int i = 0; i < vecListSize; i++)
	{
		int2 temp = vecLists[i];
		printf("idx: %d  int2: %d  %d\n", i, temp.x, temp.y);
	}
}

以上就是简单的使用方式. 额外插一句,上面那个 thrust 这个库,可以直接使用其内置的函数 做 加减乘除,甚至可以你自己重写 openrate()(…),完成自定义计算方式.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章