给定一个简单的结构来包装cuda代码,可以编写类似
的内容func<float> s;
s.val = 3.f;
start_correct<<<1, 2>>>(s);
但是,我想将块,网格,共享内存计算放入结构中并调用内核,如
func<float> s;
s.val = 3.f;
s.launch();
第一个工作时,第二个给我一个非法内存访问错误。
重现我的问题的最小例子是
#include <stdio.h>
template<typename T>
struct func;
template<typename T>
__global__ void start(const func<T>& s){
printf("host access val %f \n",s.val);
s();
}
template<typename T>
struct func
{
T val;
__device__ void operator()() const{
printf("device access val %f [%d]\n",val,threadIdx.x);
}
enum{ C_N = 2 };
void launch()
{
start<<<1, C_N>>>(*this);
}
};
template<typename T>
__global__ void start_correct(const func<T> s){
printf("host access val %f \n", s.val);
s();
}
int main(int argc, char const *argv[])
{
cudaError_t err;
func<float> s;
s.val = 3.f;
// launch cuda kernel <-- WORKS
start_correct<<<1, 2>>>(s);
cudaDeviceSynchronize();
if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));
// launch cuda kernel <-- DOES NOT WORK
s.launch();
cudaDeviceSynchronize();
err = cudaGetLastError();
if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));
return 0;
}
输出
host access val 3.000000
host access val 3.000000
device access val 3.000000 [0]
device access val 3.000000 [1]
host access val 0.000000
host access val 0.000000
device access val 0.000000 [0]
device access val 0.000000 [1]
Error: an illegal memory access was encountered
两种方式不应该相同吗?有没有其他选择,也可以在结构中进行shm,网格计算?
答案 0 :(得分:3)
除非您使用managed memory(您不是),否则通过引用传递内核参数是不合法的:
$ cuda-memcheck ./t355
========= CUDA-MEMCHECK
host access val 3.000000
host access val 3.000000
device access val 3.000000 [0]
device access val 3.000000 [1]
host access val 3.000000
host access val 3.000000
device access val 3.000000 [0]
device access val 3.000000 [1]
========= ERROR SUMMARY: 0 errors
$
当我删除该&符号时,您的代码运行时没有任何运行时错误,并提供合理的输出:
cudaDeviceSynchronize();
if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));
请注意,这并不合理:
err = cudaDeviceSynchronize();
if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));
并向我发出编译器警告。
也许你的意思是:
{{1}}