0

我有一个方法,我想在多个线程上运行,但每个线程将返回不同数量的结果。是否可以声明一个私有的、线程特定的变量,即一个列表,然后我可以将其传回主机并合并所有结果?

假设我有一个数组如下:

int[,] arr1 = new int[3,3] {{ 3, 4, 5 }, {4, 5, 6}, {1, 6, 4}};
int[] arr2 = new int[] { 3, 4, 1 };

每个线程将给出 3 个值来分析并记录 arr2 中的值与 arr1 中特定行的值之间的差异。

[Cudafy]
public static void CountAbove(GThread thread, int[] a, int[,] b, list<int> c)
{
    int tid = thread.blockIdx.x;
    int threshold = a[tid];

    for(int i = 0; i < b.GetLength(0); i++)
    {
    if (threshold < b[tid,i]) c.add(b[tid,i] - threshold);
    }
}   
4

1 回答 1

0

对的,这是可能的。在内核中声明局部变量对于您启动的每个线程都是私有的。所以只需声明一个变量,使用它,当你想将结果存储在主机中时,将它复制到全局内存中。您可以为全局内存提供一个位置,将指向它的指针作为参数传递给内核。

例子:

__global__ void kernel(float *var)
{
 float localVar;//local to each thread in execution
 ...
 //Computation which uses localVar
 ...
 *var = localVar;
}

使用后cudaMemcpy()在主机中获取它。如果您声明一个本地数组,此示例也有效。在这种情况下,您只需要复制一个数组而不是单个变量。

编辑#1:

将数组作为参数传递给内核的示例:

__global__ void kernel(float *arrayPtr, int length)
{
....
}

arrayPtr是一个 devicePtr,应该在调用内核函数之前分配。 length是数组的大小。

于 2013-06-06T11:19:27.017 回答