我对以下两种情况感到困惑。这两个函数都是通过指针传递的。一个导致主电源的改变,而另一个则没有。我认为在调用函数后,通过指针传递确实不起作用,因为它会在函数中产生指针的本地副本。任何提示表示赞赏
#include <vector>
#include <iostream>
using namespace std;
//
class A
{
public:
int b;
A() {;}
};
//
void test1(A *a)
{
A t;
t.b = 200;
a = &t;
}
//
void test2(A *a)
{
a->b = 200;
}
//
int main()
{
A a;
a.b = 10;
test1(&a);
cout<<"a.b value is NOT changed"<<endl;
cout<<a.b<<endl;
test2(&a);
cout<<"a.b value is changed"<<endl;
cout<<a.b<<endl;
}
//.. the output is:
//a.b value is NOT changed
//10
//a.b value is changed
//200
Run Code Online (Sandbox Code Playgroud) 我有以下两个几乎相同的示例代码。code1.cu使用cudaMalloc
和cudaMemcpy
来处理设备/主机变量值交换。
使用code2.cu ,cudaMallocManaged
因此cudaMemcpy
不需要。当使用 cudaMallocManaged 时,我必须包含 cudaDeviceSynchronize()
以获得正确的结果,而对于使用 cudaMalloc 的情况,则不需要这样做。我希望能得到一些关于为什么会发生这种情况的提示
代码2.cu
\n\n#include <iostream>\n#include <math.h>\n#include <vector>\n//\n\nusing namespace std;\n\n\n// Kernel function to do nested loops\n__global__\nvoid add(int max_x, int max_y, float *tot, float *x, float *y)\n{\n int i = blockIdx.x*blockDim.x + threadIdx.x;\n int j = blockIdx.y*blockDim.y + threadIdx.y;\n if(i < max_x && j<max_y) {\n atomicAdd(tot, x[i] + y[j]);\n }\n}\n\n\nint main(void)\n{\n int Nx = 1<<15;\n int Ny = 1<<15;\n float *d_x = …
Run Code Online (Sandbox Code Playgroud)