0

我遇到了一种情况,我需要提供一些数组作为全局函数的输入,我需要每个线程能够以不会影响其他线程复制的方式对数组执行操作数组,我提供下面的代码作为我想要实现的示例。

__global__ void testLocalCopy(double *temper){

     int threadIDx = threadIdx.x + blockDim.x * blockIdx.x; 

     // what I need is for each thread to set temper[3] to its id without affecting any other threads copy
    // so thread id 0 will have a set its copy of temper[3] to 0 and thread id 3 will set it to 3 etc.
     temper[3]=threadIDx;
     printf("For thread  %d  the val in temper[3] is   %lf \n",threadIDx,temper[3]);

}

只是重申一下,是否有一种方法可以让给定线程确定没有其他线程正在更新其 temp[3] 的值?

我最初认为我可以通过使用常量内存来解决这个问题,但是由于常量内存是只读的,这不能满足我的需求,

我正在使用 cuda 4.0 ,请参阅下面的主要功能。

int main(){

    double temper[4]={2.0,25.9999,55.3,66.6};
double *dev_temper;
int size=4;


    cudaMalloc( (void**)&dev_temper, size * sizeof(double) );
cudaMemcpy( dev_temper, &temper, size * sizeof(double), cudaMemcpyHostToDevice );


testLocalCopy<<<2,2>>>(dev_temper);
cudaDeviceReset();

cudaFree(dev_temper);

}

在此先感谢,康纳

4

1 回答 1

1

在您的内核函数中,您可以将内存分配为

int temp_per_thread[4];

现在每个线程都可以在内核中对这个数组进行单独且唯一的访问,例如下面的代码将填充temper_per_thread当前线程索引:

temp_per_thread[0]=threadIDx;

temp_per_thread[1]=threadIDx;

temp_per_thread[2]=threadIDx;

temp_per_thread[3]=threadIDx;

当然,如果您希望将所有这些线程特定的数组传输回 CPU,您将需要一种不同的方法。1)分配更大部分的全局内存。2) 这大部分全局内存的大小将是线程数乘以每个线程唯一的元素数。3)索引数组写入,以便每个线程始终写入全局内存中的唯一位置。4) 在内核完成后做一个 GPU 到 CPU memcpy。

于 2012-09-20T13:05:31.640 回答