将全局复制到共享内存
Copy global to shared memory
我想从全局内存复制到共享内存,我做了以下
__global__ void test(unsigned char *image, unsigned char *out, int n, int m)
{
int x = threadIdx.x + blockIdx.x * blockDim.x;
int y = threadIdx.y + blockIdx.y * blockDim.y;
int index = x + y * blockDim.x * gridDim.x;
__shared__ unsigned char shared [16*16*3];
if (threadIdx.x < 256)
{
shared[threadIdx.x*3+0] = image[index*3+0];
shared[threadIdx.x*3+1] = image[index*3+1];
shared[threadIdx.x*3+2] = image[index*3+2];
}
__syncthreads();
if (threadIdx.x < 256)
{
out[index*3+0] = shared[threadIdx.x*3+0];
out[index*3+1] = shared[threadIdx.x*3+1];
out[index*3+2] = shared[threadIdx.x*3+2];
}
}
我有一个512x512的映像,我用这种方式调用内核:
out = (unsigned char*) malloc(n*m*3);
cudaMalloc( (void**)&dev_image, n*m*3);
cudaMalloc( (void**)&dev_out, n*m*3);
cudaMemcpy( dev_image, image, n*m*3, cudaMemcpyHostToDevice);
cudaMemcpy( dev_out, out, n*m*3, cudaMemcpyHostToDevice);
dim3 threads(16,16);
dim3 blocks(32, 32);
test<<<blocks, threads>>>(dev_image, dev_out, n, m);
cudaThreadSynchronize();
cudaMemcpy( out, dev_out, n*m*3, cudaMemcpyDeviceToHost );
知道我做错了什么吗?如何将全局内存的一部分复制到共享内存(一维)?
在内核中,您检查threadIdx.x < 256
,这是错误的,因为threadIdx.x
不能大于15。您必须在16x16
线程块中检查索引。
我已将您的内核更改为:
__global__ void test(unsigned char *image, unsigned char *out, int n, int m)
{
int x = threadIdx.x + blockIdx.x * blockDim.x;
int y = threadIdx.y + blockIdx.y * blockDim.y;
int index = x + y * blockDim.x * gridDim.x;
int blockIndex = threadIdx.x + threadIdx.y * blockDim.x;
__shared__ unsigned char shared [16*16*3];
if (blockIndex < 256 && index < n*m)
{
shared[blockIndex*3+0] = image[index*3+0];
shared[blockIndex*3+1] = image[index*3+1];
shared[blockIndex*3+2] = image[index*3+2];
}
__syncthreads();
if (blockIndex < 256 && index < n*m)
{
out[index*3+0] = shared[blockIndex*3+0];
out[index*3+1] = shared[blockIndex*3+1];
out[index*3+2] = shared[blockIndex*3+2];
}
}
此外,您永远不应该忘记内核中的边界检查(我也添加了)以及内核和cudaapi调用的正确cuda错误检查。
相关文章:
- 使用Boost Interprocess创建托管共享内存需要很长时间
- 字符串共享内存映射的向量
- CUDA 使用共享内存平铺 3D 卷积实现
- 共享内存:MapViewOfFile 返回错误 5
- 如何在多写入器情况下对文件支持的共享内存中的大页面出错
- 有没有办法列出所有共享内存对象的名称?
- 共享内存的升压容器是否实现锁定?
- 共享内存中的健壮互斥锁不是那么健壮
- 使用IPC/共享内存将Integer数组从C++传递到Python
- 共享内存和性能
- 在这种特殊情况下,我是否需要在共享内存中使用原子类型
- 是否可以在专用内存空间中分配一个为提升管理共享内存而创建的对象
- fork(),在C中共享内存和指针
- 访问共享内存而不使用易失性、std::atomic、信号量、互斥锁和自旋锁
- 提升进程间共享内存open_or_create每次都会引发异常
- 通过 mmap-ed 共享内存传递可变长度 C 字符串
- 越界访问 CUDA 共享内存
- 在共享内存中插入映射映射时出现编译器错误
- 矩阵矢量产品 CUDA 通过平铺和共享内存提高性能
- 如何更改在 c++ 中使用提升库创建的共享内存的路径