我正在通过NVIDIA GeForce GT 650M GPU实现多线程,以实现我创建的模拟。为了确保一切正常,我创建了一些侧面代码来测试一切正常。有一次,我需要更新变量向量(它们都可以单独更新)。
以下是它的要点:
`\__device__
int doComplexMath(float x, float y)
{
return x+y;
}`
`// Kernel function to add the elements of two arrays
__global__
void add(int n, float *x, float *y, vector<complex<long double> > *z)
{
int index = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
for (int i = index; i < n; i += stride)
z[i] = doComplexMath(*x, *y);
}`
`int main(void)
{
int iGAMAf = 1<<10;
float *x, *y;
vector<complex<long double> > VEL(iGAMAf,zero);
// Allocate Unified Memory – accessible from CPU or GPU
cudaMallocManaged(&x, sizeof(float));
cudaMallocManaged(&y, sizeof(float));
cudaMallocManaged(&VEL, iGAMAf*sizeof(vector<complex<long double> >));
// initialize x and y on the host
*x = 1.0f;
*y = 2.0f;
// Run kernel on 1M elements on the GPU
int blockSize = 256;
int numBlocks = (iGAMAf + blockSize - 1) / blockSize;
add<<<numBlocks, blockSize>>>(iGAMAf, x, y, *VEL);
// Wait for GPU to finish before accessing on host
cudaDeviceSynchronize();
return 0;
}`
我正在尝试分配统一内存(可从GPU和CPU访问的内存)。使用nvcc编译时,我收到以下错误:
错误:没有重载函数“cudaMallocManaged”匹配参数列表参数类型的实例是:(std :: __ 1 :: vector,std :: __ 1 :: allocator >> *,unsigned long)
如何在CUDA中正确地重载函数以使用多线程这种类型?
你不可能做你想做的事。
要使用托管内存分配向量,您必须编写自己的分配器实现,该分配器继承自std::allocator_traits
并在引擎盖下调用cudaMallocManaged
。然后,您可以使用allocator类实例化std::vector
。
另请注意,您的CUDA内核代码已损坏,因为您无法在设备代码中使用std::vector
。
请注意,虽然问题是在视图中管理内存,但这适用于其他类型的CUDA分配,例如固定分配。
作为另一种选择,建议here,你可以考虑使用推力主机矢量代替std::vector
并使用自定义分配器。在固定分配器(here / cudaMallocHost
)的情况下,一个有效的例子是cudaHostAlloc
。